C Exercise Example 37 - Sorting
Title:Sort 10 numbers.
Program analysis:You can use the selection method, that is, during the subsequent 9 comparisons, select the smallest one and swap it with the first element. Next time, similarly, use the second element to compare with the following 8 elements, and perform the swap.
Example
#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("Please enter %d numbers:\n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
selectionSort(arr, N);
printf("The sorted result is:\n");
for (int i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
The output of the above example is:
请输入 10 个数字: 23 2 27 98 234 1 4 90 88 34 排序结果是: 1 2 4 23 27 34 88 90 98 234other extensions