How does the compare function in qsort work?

前端 未结 6 1224
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 03:36

I found this sample code online, which explains how the qsort function works. I could not understand what the compare function returns.

#include         


        
6条回答
  •  没有蜡笔的小新
    2020-12-06 03:49

    Whenever the sorting algorithm needs to find out which of two elements should be placed before the other, it will call the comparison function and pass pointers to the two elements. Since you are sorting int values, the pointers are actually pointers to int, but the signature must take void* so that it can be used with any data type. Therefore, in order to obtain the actual element value, a must be cast to int* and then be dereferenced - hence, *(int*)a. The function must return a negative value if a is to be placed before b, a positive value if b is to be placed before a, or zero if it doesn't matter which is placed first (which is usually the case when the elements are equal). In this particular case, since we are working with numbers, simply subtracting the value of b from the value of a is sufficient if we want the biggest numbers to go first.

提交回复
热议问题