각 루프마다 최대 원소를 찾는다.
최대 원소와 맨 오른쪽 원소를 교환한다.
맨 오른쪽 원소를 제외하고 탐색
하나의 원소가 남을 때 까지 반복한다.
<알고리즘>
selectSort(A[],n){
for last <- n down to 2{
A[1 ~ last] 중 가장 큰 수 A[k]를 찾는다;
A[k] <-> A[last];
}
}
<구현>
#include <iostream>
#include <random>
#define SIZE 10
using namespace std;
int A[SIZE];
void print_arr();
void make_num() {
for (int i = 0; i < SIZE; i++) {
A[i] = rand() % 10;
}
print_arr();
}
void print_arr() {
for (int i = 0; i < SIZE; i++) {
cout << A[i] << ' ';
}
cout << endl;
}
void select_sort(int n) {
if (n > 0) {
int max_temp = 0;
for (int i = 1; i < n; i++) {
if (A[i] >= A[max_temp]) max_temp = i;
}
int temp = A[n-1];
A[n - 1] = A[max_temp];
A[max_temp] = temp;
select_sort(n - 1);
}
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
/*selectSort [O(n^2)]*/
make_num();
select_sort(SIZE);
print_arr();
return 0;
}
'알고리즘' 카테고리의 다른 글
피보나치 수 (0) | 2020.04.04 |
---|---|
Union Find(합집합 찾기) (0) | 2019.08.15 |
Bubble Sort (거품정렬) (0) | 2018.10.27 |
[알고리즘] MergeSort (0) | 2018.10.26 |
[MST] 크루스칼 알고리즘 (0) | 2018.10.10 |
댓글