메뉴 건너뛰기

C++ - 선택 정렬(Selection Sort)

Eugene 2022.05.17 16:22 조회 수 : 119

#include <iostream>

 

using namespace std;

 

void selectionSort(int* a, const int n);

void printArray(const int* a, const int n);

 

int main()

{

    const int n = 10;

    int a[n] = { 5, 2, 7, 1, 9, 8, 10, 6, 3, 4 };

    

    cout << "Array Before Sort: ";

    

    printArray(a, n);

    selectionSort(a, n);

 

    cout << "Array After Sort: ";

    printArray(a, n);

}

 

void selectionSort(int* a, const int n) {

    for (int i = 0; i < n; i++) {

        /*

         * j: 가장 작은 값의 위치를 저장, 처음에 i의 위치를 가장 작은 값으로 가정

         */

        int j = i;

 

        /*

         * i의 다음 값부터 마지막 값까지 반복하며, 가장 작은 값의 위치를 j에 저장

         */

        for (int k = i + 1; k < n; k++)

            if (a[k] < a[j])

                j = k;

 

        /*

         * 가장 작은 값을 i의 위치와 교환 

         */

        int temp = a[i];

        a[i] = a[j];

        a[j] = temp;

    }

}

 

void printArray(const int* a, const int n) {

    for (int i = 0; i < 10; i++)

        cout << a[i] << " ";

    cout << endl;

}

 

첫 위치부터 마지막까지 이동하며, 현 위치 뒤에 있는 값들 중 가장 작은 값을 현 위치로 이동하며, 정렬한다.