Reputation: 5030
I read the usage of qsort()
in <stdlib.h>
as described here qsort(). The syntax for the function is:
void qsort (void* base, size_t num, size_t size,
int (*compar)(const void*,const void*));
This function requires a sorting function compare()
as follows:
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
With this function, qsort() sorts elements of array in a ascending order. I am confused about the compare() function
, how does it help achieve ascending sorting. Anyone can explain the principle involved in a simple language? Thanks!
P.S. It is noted a similar question has been asked here cmpfunc in qsort() function in c
Upvotes: 1
Views: 418
Reputation: 84561
There is no magic to it. The prototype is:
int compare (const void *a, const void *b)
The pointers a
and b
are pointers to adjacent elements in the array being sorted. What the compare
function does is tell qsort
how to evaluate whether the value pointed to by a
sorts before the value pointed to by b
(in which case the compare function should return -1
). If the values are equal, then it should return 0
and finally if b
should sort before a
, the compare should return 1
.
(technically any negative or positive value can be returned)
However, your compare
is subject to overflow. Best to test integer values as the result of two conditional expressions, e.g.
/* integer comparison ascending
* (adapt for all numeric types)
*/
int compare (const void *a, const void *b)
{
/* (a > b) - (a < b) */
return (*(int *)a > *(int *)b) - (*(int *)a < *(int *)b);
}
Upvotes: 2