Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qsort array of strings in descending order

Tags:

arrays

c

sorting

To sort an array of strings in ascending order, I use:

int cmp(const void *p, const void *q) {
     char* const *pp = p;
     char* const *qq = q;
     return strcmp(*pp, *qq);
}

This will be then implemented into a qsort like so:

qsort(a, sizeof(a)(sizeof(a[0]), sizeof(a[0]), cmp);

How do you sort it in descending order?

like image 556
user2122151 Avatar asked Jan 25 '26 06:01

user2122151


1 Answers

One quick and easy way to do this is to multiply the result of strcmp() by -1 before returning it.

int cmp(const void *p, const void *q) {
     char* const *pp = p;
     char* const *qq = q;
     return -strcmp(*pp, *qq);
}
like image 77
wonglkd Avatar answered Jan 27 '26 21:01

wonglkd