arrange a set of numbers in descending order using the C language
You can use the bubble sort algorithm to arrange a group of numbers from largest to smallest. Here is an example implemented in C language.
#include <stdio.h>
void bubbleSort(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]) {
// 交换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, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("原始数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
bubbleSort(arr, n);
printf("\n从大到小排列后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output result:
原始数组:5 3 8 2 1
从大到小排列后的数组:8 5 3 2 1
This example demonstrates the use of the bubble sort algorithm, which gradually moves the largest element to the end of the array by comparing adjacent elements and swapping their positions. This process is repeated until the entire array is sorted.