C 練習例37 - ソート
問題:10個の数値をソートします。
プログラム解析:選択法が利用できます。すなわち、後ろの9個の要素との比較で最小のものを選び、最初の要素と交換します。次回も同様に、2番目の要素と後ろの8個を比較して交換します。
例
#include <stdio.h>
#define N 10
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
// Swap the elements
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
int main() {
int arr[N];
printf("%d 個の数値を入力してください:\n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
selectionSort(arr, N);
printf("ソート結果は:\n");
for (int i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
上記の例の出力結果は:
请输入 10 个数字: 23 2 27 98 234 1 4 90 88 34 排序结果是: 1 2 4 23 27 34 88 90 98 234その他の拡張