To sort an array in descending order in C, you can use the `qsort` function from the `stdlib.h` library with a custom comparison function.
In this example,
numbers
.qsort
function to sort the array of integers using the custom comparison function.#include <stdio.h>
#include <stdlib.h>
int compare_desc(const void *a, const void *b) {
return (*(int*)b - *(int*)a);
}
int main() {
int numbers[] = {5, 2, 8, 1, 9};
int size = sizeof(numbers) / sizeof(numbers[0]);
qsort(numbers, size, sizeof(int), compare_desc);
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
9 8 5 2 1
In this example,
words
.qsort
function to sort the array of strings using the custom comparison function.#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef const char* string;
int compare_desc(const void* a, const void* b) {
return strcmp(*(string*)b, *(string*)a);
}
int main() {
string words[] = {"apple", "banana", "cherry", "date"};
int size = sizeof(words) / sizeof(words[0]);
qsort(words, size, sizeof(string), compare_desc);
for (int i = 0; i < size; i++) {
printf("%s ", words[i]);
}
return 0;
}
date cherry banana apple
In this tutorial, we learned How to Sort an Array in Descending Order in C language with well detailed examples.