[기억할 내용들]
- 오름차순 선택 정렬을 구현할 거라면 이중 포문을 돌면서 정렬되지 않은 부분 중 가장 작은 값을 찾고, 그 값을 정렬되지 않은 부분의 가장 앞 부분의 값과 변경해주면 된다.
- 내림차순 선택 정렬을 구현할 거라면 가장 큰 값을 찾아서 변경해주면 된다.
[나의 코드]
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vector<int> table(n);
for (int i = 0; i < n; i++)
cin >> table[i];
for (int i = 0; i < table.size() - 1; i++) {
int min = i;
for (int j = i + 1; j < table.size(); j++) {
if (table[min] > table[j]) min = j;
}
int tmp = table[i];
table[i] = table[min];
table[min] = tmp;
}
for (int i = 0; i < table.size(); i++)
cout << table[i] << " ";
cout << "\n";
return 0;
}
[강의 코드]
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int a[100], n, idx, i, j, tmp;
scanf_s("%d", &n);
for (i = 0; i < n; i++) {
scanf_s("%d", &a[i]);
}
for (i = 0; i < n-1; i++) {
idx = i;
for (j = i + 1; j < n; j++) {
if (a[j] < a[idx]) idx = j;
}
tmp = a[i];
a[i] = a[idx];
a[idx] = tmp;
}
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
[의견]
자료구조 때 배웠던 내용이라 문제 풀이에 문제가 없었다. 아직 잘 기억하고 있는 것 같아서 기분이 좋았다. 앞으로도 잊지 말고 계속해서 공부해야겠다. 파이팅!!!! ^_^
[참고자료]
SelectionSort (선택 정렬) (tistory.com)