C Array Sorting: Largest to Smallest

You can use the standard library function qsort() in C language to sort an array in descending order.

#include <stdio.h>
#include <stdlib.h>

// 比较函数,用于qsort()排序时指定排序规则
int compare(const void *a, const void *b) {
    return (*(int*)b - *(int*)a);
}

int main() {
    int arr[] = {5, 2, 8, 1, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    qsort(arr, n, sizeof(int), compare);

    printf("数组从大到小排序后:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

In the above code, we have defined a comparison function compare() which determines the sorting rule based on the size of the two parameters passed in. Then, in the main() function, we use the qsort() function to sort the array arr, with the sorting rule specified by the compare() function.

By running the above code, the output will be: 8 5 3 2 1, which is the result of sorting the array in descending order.

bannerAds