用c语言用选择法对数组中10个整数按由小到大排序
时间: 2023-11-21 19:11:52 浏览: 84
程序分析下列程序的功能是用选择法对-2243计算机软件基础(一)自考本科
下面是使用选择排序法对一个整型数组按照从小到大的顺序进行排序的C语言代码:
```c
#include <stdio.h>
void selectionSort(int arr[], int n);
int main() {
int arr[] = {64, 25, 12, 22, 11, 90, 87, 78, 56, 36};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
selectionSort(arr, n);
printf("\nSorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
void selectionSort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
```
输出结果:
```
Original array:
64 25 12 22 11 90 87 78 56 36
Sorted array:
11 12 22 25 36 56 64 78 87 90
```
阅读全文