-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection_sort.cpp
More file actions
53 lines (47 loc) · 1.05 KB
/
selection_sort.cpp
File metadata and controls
53 lines (47 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
// 配列出力関数
void OutputArray(int A[], int N)
{
for (int x=0; x<N-1; x++) {
// 空白区切りで出力
std::cout << A[x] << " ";
}
std::cout << A[N-1] << std::endl;
}
// 結果出力
void DisplayResults(int A[], int N, int Cnt)
{
OutputArray(A, N);
std::cout << Cnt << std::endl;
}
// 選択ソート実行関数
void SelectionSort(int R[], int N)
{
// ソート回数をカウント
int cnt_sort = 0;
for (int i=0; i<N; i++) {
// 初期化しないとRuntime Error
int v = 0;
int minVal = 100;
for (int j=i; j<N; j++) {
if (R[j] < minVal) {
minVal = R[j];
v = j;
}
}
if (R[i] != R[v]) {
std::swap(R[i], R[v]);
cnt_sort++;
}
}
DisplayResults(R, N, cnt_sort);
}
int main()
{
static const int MAX = 100;
int n, R[MAX];
std::cin >> n;
for (int i=0; i<n; i++) std::cin >> R[i];
SelectionSort(R, n);
return 0;
}