-
Qsort
I saw this example on a website:
Code:
/* qsort example */
#include <stdio.h>
#include <stdlib.h>
int values[] = { 40, 10, 100, 90, 20, 25 };
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main ()
{
int * pItem;
int n;
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++)
{
printf ("%d ",values[n]);
}
return 0;
}
I understand all of it but the compare function. Could someone explain to me in simple terms what the compare function is doing?
Thanks,
Shane
-
That compare function is subtracting a from b. First it casts each void * as an int *, and then dereferences them. The end result is a positive integer if a > b, 0 if a = b, and a negative integer if a < b.
-
Except it's safer to write it out in a slightly longer form
Code:
int compare (const void * a, const void * b)
{
int v1 = *(int*)a;
int v2 = *(int*)b;
if ( v1 < v2 ) return -1;
if ( v1 > v2 ) return +1;
return 0;
}
A simple subtraction has the possibility of underflow, and thus the possibility of producing the wrong answer.
-