C语言对含有10个元素的一维数组使用选择排序法分别按升序和降序排序
时间: 2024-02-23 09:27:06 浏览: 73
C语言程序设计-编写函数用选择排序法对数组中的数据进行从小到大的排序;
5星 · 资源好评率100%
以下是对含有10个元素的一维数组使用选择排序法分别按升序和降序排序的C语言代码:
```c
#include <stdio.h>
void selectionSortAsc(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;
}
}
void selectionSortDesc(int arr[], int n) {
int i, j, max_idx;
for (i = 0; i < n - 1; i++) {
max_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] > arr[max_idx])
max_idx = j;
int temp = arr[max_idx];
arr[max_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[10] = {9, 2, 8, 4, 5, 7, 1, 3, 10, 6};
int i;
printf("Original array: ");
for (i = 0; i < 10; i++)
printf("%d ", arr[i]);
selectionSortAsc(arr, 10);
printf("\nArray sorted in ascending order: ");
for (i = 0; i < 10; i++)
printf("%d ", arr[i]);
selectionSortDesc(arr, 10);
printf("\nArray sorted in descending order: ");
for (i = 0; i < 10; i++)
printf("%d ", arr[i]);
return 0;
}
```
输出结果为:
```
Original array: 9 2 8 4 5 7 1 3 10 6
Array sorted in ascending order: 1 2 3 4 5 6 7 8 9 10
Array sorted in descending order: 10 9 8 7 6 5 4 3 2 1
```
阅读全文