c语言将一个一维数组的元素按照从大到小的顺序排序,并输出排序结果
时间: 2024-02-18 18:00:12 浏览: 75
C语言将数组中元素的数排序输出的相关问题解决
好的,可以使用冒泡排序或选择排序来实现,以下分别是两种排序算法的示例代码:
冒泡排序:
```c
#include <stdio.h>
void bubble_sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 3, 8, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出:
```
8 5 4 3 2
```
选择排序:
```c
#include <stdio.h>
void selection_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;
}
}
int temp = arr[i];
arr[i] = arr[max_idx];
arr[max_idx] = temp;
}
}
int main() {
int arr[] = {5, 3, 8, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
selection_sort(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出:
```
8 5 4 3 2
```
阅读全文