선택 정렬 기술에서 목록은 두 부분으로 나뉩니다. 한 부분에서는 모든 요소가 정렬되고 다른 부분에서는 항목이 정렬되지 않습니다. 처음에는 배열에서 최대 또는 최소 데이터를 가져옵니다. 데이터를 가져온 후(최소값이라고 함) 첫 번째 데이터를 최소 데이터로 교체하여 목록의 시작 부분에 배치합니다. 수행 후 어레이가 작아지고 있습니다. 이렇게 정렬 기술이 완성됩니다.
선택 정렬 기법의 복잡성
-
시간 복잡도:O(n 2 )
-
공간 복잡도:O(1)
Input − The unsorted list: 5 9 7 23 78 20 Output − Array after Sorting: 5 7 9 20 23 78
알고리즘
selectionSort(배열, 크기)
입력 :데이터 배열 및 배열의 총 개수
출력 :정렬된 배열
Begin for i := 0 to size-2 do //find minimum from ith location to size iMin := i; for j:= i+1 to size – 1 do if array[j] < array[iMin] then iMin := j done swap array[i] with array[iMin]. done End
예시 코드
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void selectionSort(int *array, int size) {
int i, j, imin;
for(i = 0; i<size-1; i++) {
imin = i; //get index of minimum data
for(j = i+1; j<size; j++)
if(array[j] < array[imin])
imin = j;
//placing in correct position
swap(array[i], array[imin]);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
} 출력
Enter the number of elements: 6 Enter elements: 5 9 7 23 78 20 Array before Sorting: 5 9 7 23 78 20 Array after Sorting: 5 7 9 20 23 78