用c语言实现从一个数组中从大到小选10个数出来
时间: 2023-12-03 20:46:37 浏览: 79
下面是一种基于选择排序算法的实现方法:
```c
#include <stdio.h>
void select_sort(int arr[], int n);
int main()
{
int arr[] = {10, 2, 8, 4, 6, 7, 9, 1, 3, 5};
int n = sizeof(arr) / sizeof(arr[0]);
select_sort(arr, n);
printf("The top 10 numbers in the array are: ");
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void select_sort(int arr[], int n)
{
for (int i = 0; i < n-1; i++) {
int max_idx = i;
for (int j = i+1; j < n; j++) {
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
if (max_idx != i) {
int temp = arr[i];
arr[i] = arr[max_idx];
arr[max_idx] = temp;
}
}
}
```
运行结果为:
```
The top 10 numbers in the array are: 10 9 8 7 6 5 4 3 2 1
```
在 `select_sort` 函数中,我们使用了选择排序算法,将数组中的元素从大到小排序。最后,我们输出排序后的前10个元素即可。
阅读全文