선택 정렬 알고리즘은 정렬되지 않은 부분에서 기본 구성요소를 찾아 시작 부분에 두 번 이상 전시를 정렬합니다. 결정 정렬을 강조할 때마다 정렬되지 않은 하위 배열의 기본 구성 요소가 선택되어 정렬된 하위 배열로 이동됩니다.
예시
#include <iostream>
#include <string.h>
using namespace std;
#define MAX_LEN 50
void selectionSort(char arr[][50], int n){
int i, j, mIndex;
// Move boundary of unsorted subarray one by one
char minStr[50];
for (i = 0; i < n-1; i++){
// Determine minimum element in unsorted array
int mIndex = i;
strcpy(minStr, arr[i]);
for (j = i + 1; j < n; j++){
// check whether the min is greater than arr[j]
if (strcmp(minStr, arr[j]) > 0){
// Make arr[j] as minStr and update min_idx
strcpy(minStr, arr[j]);
mIndex = j;
}
}
// Swap the minimum with the first element
if (mIndex != i){
char temp[50];
strcpy(temp, arr[i]); //swap item[pos] and item[i]
strcpy(arr[i], arr[mIndex]);
strcpy(arr[mIndex], temp);
}
}
}
int main(){
char arr[][50] = {"Tom", "Boyaka", "Matt" ,"Luke"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
cout<<"Given String is:: Tom, Boyaka, Matt, Luke\n";
selectionSort(arr, n);
cout << "\nSelection Sorted is::\n";
for (i = 0; i < n; i++)
cout << i << ": " << arr[i] << endl;
return 0;
} 위의 C++ 프로그램은 처음에 전시회에서 가장 작은 구성 요소를 선택하고 클러스터의 주요 구성 요소와 교체합니다. 다음으로, 클러스터에서 두 번째로 작은 구성요소를 후속 구성요소 등과 교환합니다. 이러한 방식으로 각 패스에 대해 전시회에서 가장 작은 구성요소가 선택되고 전체 클러스터가 배열될 때까지 합법적인 상황에 놓입니다. 마지막으로 섹션 정렬 방법은 다음과 같이 주어진 문자열을 오름차순으로 정렬합니다.
출력
Given string is:: Tom, Boyaka, Matt, Luke Selection Sorted:: Boyaka Luke Matt Tom