简体   繁体   中英

how compare works in qsort() function

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!

PS It is noted a similar question has been asked here cmpfunc in qsort() function in c

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, eg

/* 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM