C语言 创建一个一维数组,将数组中的数据从大到小排序
时间: 2024-05-09 22:18:09 浏览: 68
C语言程序设计-编写函数用选择排序法对数组中的数据进行从小到大的排序;
5星 · 资源好评率100%
好的,你可以使用冒泡排序或快速排序来实现从大到小排序:
冒泡排序:
```c
#include <stdio.h>
void bubble_sort(int arr[], int n);
int main()
{
int arr[] = {5, 2, 8, 7, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
bubble_sort(arr, n);
printf("Sorted array (from largest to smallest): ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void bubble_sort(int arr[], int n)
{
int temp = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] < arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
快速排序:
```c
#include <stdio.h>
void quick_sort(int arr[], int left, int right);
int main()
{
int arr[] = {5, 2, 8, 7, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
quick_sort(arr, 0, n - 1);
printf("Sorted array (from largest to smallest): ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void quick_sort(int arr[], int left, int right)
{
int i = left, j = right;
int temp, pivot = arr[(left + right) / 2];
while (i <= j)
{
while (arr[i] > pivot)
{
i++;
}
while (arr[j] < pivot)
{
j--;
}
if (i <= j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (left < j)
{
quick_sort(arr, left, j);
}
if (i < right)
{
quick_sort(arr, i, right);
}
}
```
希望对你有所帮助。
阅读全文