The use of the C + + sort function

Source: Internet
Author: User

The STL has a sort function that can be sorted directly into the array, with a complexity of N*LOG2 (n). With this function, you need to include a header file #include <algorithm> This function can pass two parameters or three parameters. The first parameter is the first address of the interval to sort, and the second is the next address of the interval end address. In other words, the sorting interval is [A, b]. Simply put, there is an array int a[100], to sort the elements from a[0] to a[99], just write sort (a,a+100) and the default sort is ascending. Similar to vector v ordering, sort (v.begin (), V.end ()); If you do not define a data type that is less than the operation, or if you want to change the order of the sort, use the third parameter-the comparison function. The comparison function is a function of its own definition, the return value is a bool type, it specifies what kind of relationship is "less than". If you want to sort the array of integers in descending order, you can first define a comparison function CMP

BOOL CMP (int a,int b) {    return a>b;}

   when sorting, write sort (a,a+100,cmp);

Assume that you have defined a struct node

struct node{    int A;    int b;    Double C;}

There is an array of node type node arr[100], want to sort it: first by a value in ascending order, if the a value is the same, and then the B value in descending order, if B is also the same, in descending order of C. You can write a comparison function like this:

BOOL CMP (node X,node y) {     if (x.a!=y.a)      return x.a<y.a;     if (x.b!=y.b)       return x.b>y.b;     return return X.C>Y.C;}  

Sort by writing sort (arr,a+100,cmp);

Reference http://blog.sina.com.cn/s/blog_6439f26f01012xw3.html

The use of the C + + sort function

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.