Various sorting functions (pick)

Source: Internet
Author: User

The application of sort;

1, can be passed two parameters;

Sort (a,a+n), where a is an array and a+n represents the N number of a[0] to a[n-1] (default from small to large);

2, pass in three parameters;

Sort (a,a+n,cmp), the third parameter is a function;

If the function from large to small sorting, can be implemented with the following algorithm;

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

Sort (a,a+n,cmp);

sorting function functions: Partial_sort:

For example, you have a vector container that contains Widget objects (widgets mean "small pendants"), and you want to send the 20 best widgets with the best quality, so all you have to do is figure out the 20 best-quality widget elements, The rest do not need to care about their order. What you need now is a partial sort (relative to the full sort)

BOOLQualitycompare (Constwidget& LHS,Constwidget&RHS) {              //Returns true if the mass of the LHS is not worse than the quality of the RHS, otherwise false}...partial_sort (Widgets.begin (),//The 20 elements of the best qualityWidgets.begin ()+ -,//order into the Widgets containerwidgets.end (), qualitycompare); ... ..//using Widgets

By calling Partial_sort, the 20 elements that start in the container are the 20 best-quality widgets you need, sorted in order, the first of the quality rows is widgets[0], followed by widgets[1], and so on. This way you can give the quality first widget to your best customers, and the second quality widget can be sent to the next customer.

If you just want to give these 20 best-quality widget gifts to your best 20 customers without having to match them, Partial_sort is a bit overqualified here. Because here, you just need to find these 20 elements, without having to sort them by themselves. At this time you need not partial_sort, but nth_element.

Nth_element Sorting algorithm

Just sort a range until you put the correct element in the nth position you specify, that is, the common denominator is that the nth position is the same element as you do with full and nth_element sorting. When the Nth_element function is run, the element that should be after position n in the full order does not appear in front of n, and the element before position n should not appear after N.

Nth_element (Widgets.begin (),//Put the               Best quality 20 elements in                      the       Widgets the front of the container,                       widgets.end (),                //  but does not care about these 20 elements                      qualitycompare);            // the order of the interior itself

Partial_sort the first 20 elements, and nth_element does not relate to their internal order. Each of the two algorithms implements the same function: placing the 20 best-quality elements at the beginning of the vector container.

The Nth_element function is quite numerous, except for you to find the top n elements of the unrelated order, it can also find the median of a range, or find the value at a certain percentage point.

Vector<widget>::iterator Begin (Widgets.begin ());//Widgets's firstVector<widget>::iterator End (Widgets.end ());//and the last iterator//Vector<widget>::iterator goalposition;//The iterator that needs to be positioned//The following code is used to get an iterator of the element in the middle of the massGoalposition = begin + Widgets.size ()/2;//the element you are looking for should//in the middle of the vector. Nth_element (begin, Goalposition, end,//find the middle value of the container widgets elementQualitycompare);//...//Goalposition now points to the middle value element//The following code is used to get the element with a quality of 75%Vector<widget>::size_type GoalOffset =//calculate the value to find                                        0.25* Widgets.size ();//the distance from the begin iterator. //Nth_element (begin, Begin + GoalOffset, end,//get the element with the quality at 75%Qualitycompare);//... ..//Goalposition now points to the element with a quality rank of 75%. 

Stable_sort

In a "stable" sorting algorithm, if two elements have the same value, their relative positions will remain unchanged after sorting. For example, if widget A is not sorted before widget B, and both have the same quality level, then the "stabilize" sorting algorithm guarantees that after sorting, widget a remains before widget B. Rather than a "stable" sorting algorithm, this is not guaranteed.

Partial_sort and nth_element are not "stable" sorting algorithms, the real "stable" sorting algorithm is stable_sort.

#include <algorithm>

Stable_sort, because you want to sort the struct, use the overloads of the function's three arguments, for example: Stable_sort (Vectorarray.begin (), Vectorarray.end (), mycmp);

Partition algorithm

The

partition just determines an interval for you to place elements that meet certain criteria in this interval. For example, to put the elements of the widget with the same quality level as Level 2 on the front of the widget container, we can define a function to identify the widget's quality level:

 bool  hasacceptablequality (const  Widget& W) {  If the mass of W is equal to or better than 2, returns True, otherwise false   "and then pass this judgment function to the partion algorithm: vector  < Widget>::iterator goodend = //  partition (Widgets.begin (), // widgets.end (), //  Returns the first  hasacceptablequality that does not meet the criteria); //  

In this way, all elements between the iterator Widgets.begin () and the iterator goodend are elements that meet the requirements: Their quality level is better than or equal to 2. The quality level of the elements between Goodend to Widgets.end () is lower than the quality level of 2. If you are concerned about the relative position of the same elements of the quality level, you can choose the stable_partition algorithm instead of the partition.

Summarize:

To sort vectors, strings, deque, or array containers, you can choose sort or stable_sort;

If you only need to get top n elements in the vector, string, deque, or array container, the partial sort partial_sort is preferred.

For a vector, string, deque, or array container, you need to find the nth position element or you need to get top N and do not relate to the internal order of top N, Nth_element is ideal;

If you need to separate an element that satisfies a condition or does not satisfy a condition from a standard sequence container or array, you might want to use partition or stable_partition;

If you use the list container, you can use the partition and Stable_partition algorithms directly, and you can use List::sort instead of sort and stable_sort sorting. If you need to get a partial_sort or nth_element sort effect, you have to use it indirectly. As described above, there are several ways to choose.

Example

#include <iostream>#include<vector>#include<iterator>#include<cstdlib>#include<algorithm>#include<functional>using namespacestd;BOOLLESS5 (inta) {returna<5; }intMain () {Constsize_t n=Ten; inta[Ten]={3,6,9,2,5,8,1,4,7,0}; Vector<int> Ive (a,a+N); cout<<"After sort;\n"; Sort (A,a+N);  for(intI=0; i<n;++i) cout<<a[i]<<" "; cout<<Endl; cout<<"The Top 4 number:"<<Endl; Partial_sort (Ive.begin (), Ive.begin ()+4, Ive.end (),greater<int>()); Copy (Ive.begin (), Ive.begin ()+4,ostream_iterator<int> (cout," ")); cout<<"\nthe 4th number:"<<Endl; Nth_element (Ive.begin (), Ive.begin ()+3, Ive.end (),greater<int> ());//Note is ive.begin () +3cout<<ive[3]; cout<<"\nthe top 4 number:"<<Endl; Copy (Ive.begin (), Ive.begin ()+4,ostream_iterator<int> (cout," ")); cout<<"\nthe numbers is divided less or greater 5:"<<Endl;     Partition (Ive.begin (), Ive.end (), LESS5); Copy (Ive.begin (), Ive.end (), Ostream_iterator<int> (cout," ")); cout<<Endl; System ("Pause"); return 0; }

Various sorting functions (pick)

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.