How to sort n numbers in descending order in the C language.
The bubble sort algorithm can be used to sort in descending order.
The basic idea of bubble sort is to start from the first element, compare each pair of adjacent elements, and swap their positions if the previous element is greater than the next element. After one pass, the largest element will be swapped to the last position. Then start again from the first element for the second comparison, repeating this process until all elements are sorted.
The following is an example code implementing a bubble sort algorithm to sort in descending order.
#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]) {
// 交换两个元素的位置
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int n;
printf("请输入需要排序的数字个数:");
scanf("%d", &n);
int arr[n];
printf("请输入%d个数字:", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr, n);
printf("从大到小排序后的结果为:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
This code first retrieves the number of inputs, n, then creates an array, arr, with a size of n to store the input numbers. It then uses a for loop to sequentially store n numbers in the array. Next, it calls the bubbleSort function to sort the array. Finally, it uses a for loop to output the sorted results.
Please note that when using the bubble sort algorithm, the array elements should be of a comparable type, such as integers, floating point numbers, etc., rather than pointer types, struct types, etc.