理解qsort 中的 cmp

百度了很多的资料都没有明白qsort 中 cmp 的用处,用Bing 一搜就搜到一篇自认为比其他都解析清楚的文章

直接贴出来算了

comparPointer to a function that compares two elements.
This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:

 
int compar (const void* p1, const void* p2);
 


Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):

return valuemeaning
<0 The element pointed by p1 goes before the element pointed by p2
0 The element pointed by p1 is equivalent to the element pointed by p2
>0 The element pointed by p1 goes after the element pointed by p2

假如你要按升序排列数组,需要处理两个参数P1 ,P2,如果P1 > P2 ,那cmp需要返回的是一个<0的值,所以是P1-P2

若P1<P2 ,那么cmp需要返回一个 >0的值,所以同样是P1-P2,一点都不矛盾。

假如你要按降序排列数组,需要处理两个参数P1 ,P2,如果P1 > P2 ,排序应该是P1在P2前面,那cmp需要返回的是一个<0的值,所以是P2-P1 ,若P1<P2 ,那么cmp需要返回一个 >0的值,所以同样是P2-P1

原文地址:https://www.cnblogs.com/been/p/4470199.html