Understanding the CMP in Qsort

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.