How does the compare function in qsort work?

前端 未结 6 1218
隐瞒了意图╮
隐瞒了意图╮ 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 04:07

    qsort will give each pair it needs to compare to cmpfunc and uses it's return value to see which one is greater and then sorts the array accordingly.

    Basically, if the compare function returns a positive result this means that the first argument is greater than the second one. Similarly, if it returns negative, then the second argument is greater.

    In the example, we want to sort integers. So, we need to decide which one is greater when we compare two elements of the given array. To compare those, a simple substraction operation is enough since the result is positive when a is greater, 0 if a and b are equal and negative if b is greater.

提交回复
热议问题