Baidu has a lot of information do not understand the usefulness of CMP in Qsort, with Bing a search to find a self-think than other analytical clear article
Just stick it out, okay?
Comparpointer to a function, compares, and elements.
This function was called repeatedly by to qsort compare and elements. It shall follow the following prototype:
|
int compar (constvoidconstvoid* p2);
|
|
Taking 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 value |
meaning |
<0 |
The element pointed by p1 goes before the element pointed byp2 |
0 |
The element pointed by was equivalent to the p1 element pointed byp2 |
>0 |
The element pointed by p1 goes after the element pointed byp2
|
If you want to sort the array in ascending order, you need to handle two parameters P1, P2, if P1 > P2, then the CMP needs to return a <0 value, so it is P1-P2
If P1<P2, then the CMP needs to return a value of >0, so the same is P1-P2, no contradiction at all.
If you want to sort the array in descending order, you need to handle two parameters P1, P2, if P1 > P2, the sort should be P1 in front of P2, that CMP needs to return a <0 value, so is P2-P1, if P1<P2, then CMP needs to return a >0 value, So it's the same p2-p1.
Understanding the CMP in Qsort