STL sorting (SORT)

Source: Internet
Author: User
Original article address: http://www.cppblog.com/mzty/archive/2005/12/15/1770.htmlwriter winter

    • STL sorting (SORT)

      • Why do you have to master STL?
      • 1. Sort Algorithm provided by STL
        • 1.1 Introduction to all sort Algorithms
        • 1.2 comparison functions in sort
        • 1.3 sort Stability
        • 1.4 full sorting
        • 1.5 partial sorting
        • 1.6 nth_element specifies the sorting of Elements
        • 1.7 partition and stable_partition
      • 2 sort and container
      • 3. select an appropriate sorting Function
      • 4. Summary
      • 5 References

All complex sorting operations can be easily implemented through STL!

Why do you have to master STL? For Program Data structure is a required course. From searching to sorting, from linked list to binary tree, almost all Algorithm And the principles must be understood. Fortunately, these theories are mature and the algorithms are basically fixed. You don't have to worry about the algorithm principles or verify the accuracy. However, when you start to use computer languages to work, you will find that you need to use Code Repeat these mature algorithms and get stuck in some bugs due to negligence. At this time, you want to find a tool that has helped you implement these functions. You can use it whenever you want, without affecting performance. What you need is STL, a standard template library!

There is a saying in the West: Do not reinvent the wheel!

STL encapsulates almost all algorithms in the data structure, from linked list to queue, from vector to stack, to hash to binary tree, from search to sorting, from adding to deleting ...... it can be said that if you understand STL, you will find that you do not have to stick to the algorithm itself, so that you can stand on the shoulders of giants to consider more advanced applications.

Sorting is one of the most widely used algorithms. This article describes the usage and differences of different sorting algorithms in STL.

1. Sort Algorithm provided by STL The reason why C ++ is liked by so many people is that it has both the object-oriented concept and the high efficiency of C language. STL sorting algorithms also need to be efficient. Therefore, STL provides different functions and functions for different requirements, and the implemented algorithms are different.

1.1 Introduction to all sort Algorithms

All sort algorithm parameters must enter a range, [begin, end ). The iterator used here must be a radomaccessiterator, that is, an iterator that can be accessed randomly, such as IT + N. (Except for partition and stable_partition)

If you need to define a comparison function, you can pass in the defined function as a parameter. Each algorithm supports the input of comparison functions. The following lists the names of all STL Sort Algorithm functions:

Function Name Function Description
Sort Sorts all elements in a given range.
Stable_sort Performs a stable sorting of all elements in a given range.
Partial_sort Sorts all elements in a given range.
Partial_sort_copy Copy and sort a given interval
Nth_element Find the elements corresponding to a location in a given range
Is_sorted Determine whether the order of an interval has been sorted
Partition Place elements that meet certain conditions in front of them.
Stable_partition Relatively stable putting elements that meet certain conditions in front

Among them, nth_element is the least understandable. In fact, this function is used to find the first few. For example, find out the value of the number in the middle of the array containing seven elements. At this time, I may not care about the front or the back. I only care about the value of the fourth element.

1.2 comparison functions in sort

When you need to sort by a specific method, you need to specify a comparison function for sort, otherwise the program will automatically provide you with a comparison function.

 
Vector <Int> Vect;//...Sort (vect. Begin (), vect. End ());// CallSort (vect. Begin (), vect. End (), less <Int> ());
 
 

In the preceding example, the system provides the less function for sort. Other functions are also provided in STL. The following is a list of functions:

Name Function Description
Performance_to Equal
Not_0000_to Not equal
Less Less
Greater Greater
Less_equal Less than or equal
Greater_equal Greater than or equal

It should be noted that these functions are not applicable to your sort algorithm. How to choose them depends on your application. In addition, you cannot directly write the name of the imitation function. Instead, you need to write its overloaded () function:

Less <int> () Greater <int> ()

When elements in your container are of some standard type (INT float char) or string, you can directly use these function templates. However, if you define your own types or you need to sort them by other means, you can use either of the following methods to achieve the effect: Write A comparison function by yourself. The other is the '<' operation of the overload type.

 # Include <Iostream> # Include <Algorithm> # Include <Functional> # Include <Vector> Using   Namespace STD; Class Myclass { Public : Myclass ( Int A, Int B): First (a), second (B ){} Int First; Int Second; Bool   Operator <( Const Myclass & M) Const { Return First <M. First ;}}; Bool Less_second ( Const Myclass & M1, Const Myclass & m2 ){ Return M1.second <m2.second ;}Int Main () {vector <myclass> vect; For ( Int I = 0; I <10; I ++) {myclass my (10-i, I * 3); vect. push_back (my );} For ( Int I = 0; I <vect. Size (); I ++) cout <" ( "<Vect [I]. First <" , "<Vect [I]. Second <" ) \ N "; Sort (vect. Begin (), vect. End (); cout <" After sorted by first: "<Endl; For ( Int I = 0; I <vect. Size (); I ++) cout <" ( "<Vect [I]. First <" , "<Vect [I]. Second <" ) \ N "; Cout <" After sorted by second: "<Endl; sort (vect. Begin (), vect. End (), less_second ); For ( Int I = 0; I <vect. Size (); I ++) cout <" ( "<Vect [I]. First <", "<Vect [I]. Second <" ) \ N "; Return 0 ;}
 
 

Know what the output result is:

 
() After sorted by first) () after sorted by second))
1.3 sort Stability

You may find sort and stable_sort, partition, and stable_partition strange. The difference is that functions with stable can ensure that the original relative order of equal elements remains unchanged after sorting. Maybe you will ask, since they are equal, you still care about their relative positions, and you cannot tell who they are? Here we need to clarify a problem. The equality here means that the two elements are equal and not necessarily the same element.

For example, if you write a comparison function:

BoolLess_len (ConstString & str1,ConstString & str2 ){ReturnStr1.length () <str2.length ();}
 
 

At this time, "apple" and "Winter" are equal. If "apple" appears before "Winter", their order will remain unchanged after being sorted by functions with stable, if you are using a function without "stable", "Winter" may be before "apple" after sorting.

 

1.4 full sorting

In full order, all elements in a given range are arranged in order of size and relationship. Functions used for full sorting include:

 

 Template < Class Randomaccessiterator> Void Sort (randomaccessiterator first, randomaccessiterator last ); Template <Class Randomaccessiterator, Class Strictweakordering> Void Sort (randomaccessiterator first, randomaccessiterator last, strictweakordering comp ); Template < Class Randomaccessiterator> Void Stable_sort (randomaccessiterator first, randomaccessiterator last ); Template < Class Randomaccessiterator, Class Strictweakordering> Void Stable_sort (randomaccessiterator first, randomaccessiterator last, strictweakordering comp );
 
 

In the 1 and 3 forms, neither sort nor stable_sort specify a comparison function. By default, the system uses operator <to sort all elements in the interval [first, last). Therefore, if the type yejun you are using has reloaded the operator function, you can worry about it. You can specify comparison functions at will in four forms: 2nd and, so that applications are more flexible. Let's take a look at the actual application:

There are 10 students in the class. I want to know their ranking.

 # Include <Iostream> # Include <Algorithm> # Include <Functional> # Include <Vector> # Include <String> Using   Namespace STD; Class Student { Public : Student ( Const String &, Int B): Name (A), score (B) {} string name; Int Score; Bool   Operator <( Const Student & M) Const { Return Score <M. Score ;}}; Int Main () {vector <student> vect; Student ST1 ("Tom ", 74); vect. push_back (ST1); st1.name =" Jimy "; St1.score = 56; vect. push_back (ST1); st1.name =" Mary "; St1.score = 92; vect. push_back (ST1); st1.name =" Jessy "; St1.score = 85; vect. push_back (ST1); st1.name =" Jone "; St1.score = 56; vect. push_back (ST1); st1.name =" Bush "; St1.score = 52; vect. push_back (ST1); st1.name =" Winter "; St1.score = 77; vect. push_back (ST1); st1.name =" Andyer "; St1.score = 63; vect. push_back (ST1); st1.name =" Lily "; St1.score = 76; vect. push_back (ST1); st1.name =" Maryia "; St1.score = 89; vect. push_back (ST1); cout <" ------ Before sort... "<Endl; For ( Int I = 0; I <vect. Size (); I ++) cout <vect [I]. Name <" : \ T "<Vect [I]. score <Endl; stable_sort (vect. Begin (), vect. End (), less <student> (); cout <" ----- After sort .... "<Endl;For ( Int I = 0; I <vect. Size (); I ++) cout <vect [I]. Name <" : \ T "<Vect [I]. score <Endl; Return 0 ;}
 
 

The output is:

 
------ Before sort... tom: 74 jimy: 56 Mary: 92 every Y: 85 Jone: 56 BUSH: 52 Winter: 77 andyer: 63 LILY: 76 maryia: 89 ----- after sort .... bush: 52 jimy: 56 Jone: 56 andyer: 63tom: 74 LILY: 76 Winter: 77 running Y: 85 maryia: 89 Mary: 92

Sort uses a mature "quick sorting algorithm" (currently, most STL versions do not adopt simple quick sorting, but use interpolation sorting algorithms ). Note 1: the average performance and complexity can be ensured to be n * log (N). Due to the worst case in theory in simple fast sorting, the performance is very low, the algorithm complexity is N * n, but most STL versions have been optimized in this aspect, so you can safely use it. Stable_sort uses "Merge Sorting". If enough memory is allocated, the algorithm complexity is N * log (N). Otherwise, the complexity is N * log (n) * log (n) has the advantage that the relative positions of equal elements are consistent before and after sorting.

1.5 partial sorting

Partial sorting is actually a sort method provided to reduce unnecessary operations. Its function prototype is:

 Template < Class Randomaccessiterator> Void Partial_sort (randomaccessiterator first, randomaccessiterator middle, randomaccessiterator last ); Template < Class Randomaccessiterator, Class Strictweakordering> Void Partial_sort (randomaccessiterator first, randomaccessiterator middle, randomaccessiterator last, strictweakordering comp ); Template < Class Inputiterator, Class Randomaccessiterator> randomaccessiterator partial_sort_copy (inputiterator first, inputiterator last, randomaccessiterator result_first, randomaccessiterator result_last ); Template < Class Inputiterator, Class Randomaccessiterator, Class Strictweakordering> randomaccessiterator partial_sort_copy (inputiterator first, inputiterator last, randomaccessiterator result_first, randomaccessiterator result_last, compare comp );
 
 

After understanding sort and stable_sort, it is easier to understand partial_sort. Let's take a look at its purpose: there are 10 students in the class. I want to know who has the lowest scores. If there is no partial_sort, you need to use sort to sort all people in order and then take the first five. Now you only need to sort the lowest scores by 5 and modify the above program as follows:

Stable_sort (vect. begin (), vect. end (), less <student> (); replace with: partial_sort (vect. begin (), vect. begin () + 5, vect. end (), less <student> ());
 
 

Output result:

 
------ Before sort... tom: 74 jimy: 56 Mary: 92 every Y: 85 Jone: 56 BUSH: 52 Winter: 77 andyer: 63 LILY: 76 maryia: 89 ----- after sort .... bush: 52 jimy: 56 Jone: 56 andyer: 63tom: 74 Mary: 92 127y: 85 Winter: 77 LILY: 76 maryia: 89

Do you know the benefits? When the data size is small, it may not be able to see the advantage. If it is 1 million students, I want to find the minimum score of 5 people ......

The heapsort used by partial_sort, whose complexity is N * log (n) in any situation ). if you want to use partial_sort for full sorting, you only need to make middle = last.

Partial_sort_copy is a combination of copy and partial_sort. The number of sorted (replicated) values is the one with a smaller interval in [first, last) and [result_first, result_last. If the [result_first, result_last) interval is greater than the [first, last) interval, partial_sort is equivalent to a combination of copy and sort.

1.6 nth_element specifies the sorting of Elements

Nth_element is a sort that is easy to understand but difficult to explain. The example is more convenient:
There are 10 students in the class. I want to know the number of students with the lowest scores.
If you want to meet the above requirements, you can use sort to sort the order, and then take the 4th bits (because it is from small to large). More intelligent friends will use partial_sort to rank only the first four bits, then we get 4th bits. In fact, this is a waste, because you do not need to sort the first two. In this case, you need nth_element:

 
Template<ClassRandomaccessiterator>VoidNth_element (randomaccessiterator first, randomaccessiterator nth, randomaccessiterator last );Template<ClassRandomaccessiterator,ClassStrictweakordering>VoidNth_element (randomaccessiterator first, randomaccessiterator nth, randomaccessiterator last, strictweakordering comp );
 
 

For the above instance requirements, you only need to modify the program in 1.4 as follows:

Stable_sort (vect. begin (), vect. end (), less <student> (); replace with: nth_element (vect. begin (), vect. begin () + 3, vect. end (), less <student> ());
 
 

The running result is:

 
------ Before sort... tom: 74 jimy: 56 Mary: 92 every Y: 85 Jone: 56 BUSH: 52 Winter: 77 andyer: 63 LILY: 76 maryia: 89 ----- after sort .... jone: 56 BUSH: 52 jimy: 56 andyer: 63 127y: 85 Mary: 92 Winter: 77tom: 74 LILY: 76 maryia: 89

Who is the fourth? Andyer, this unlucky guy. Why is it begin () + 3 instead of + 4? I started writing this article.ArticleI did not care about it. Later I found this problem with the reminder of ilovevc. Begin () is the first, begin () + 1 is the second, and... begin () + 3 is of course the fourth.

1.7 partition and stable_partition

It seems that these two functions are not used for sorting. The 'category' algorithm will be more appropriate. Partition divides the elements in a range into two types according to a certain condition. Its function prototype is:

Template<ClassForwarditerator,ClassPredicate> forwarditerator partition (forwarditerator first, forwarditerator last, predicate Pred)Template<ClassForwarditerator,ClassPredicate> forwarditerator stable_partition (forwarditerator first, forwarditerator last, predicate Pred );
 
 

Let's take a look at the application: there are 10 students in the class who have passed the calculation (below 60 points. You only need to replace the program 1.4 in the following format:

 
Stable_sort (vect. Begin (), vect. End (), less <student> (); replace it with student exam ("Pass", 60); stable_partition (vect. Begin (), vect. End (), bind2nd (less <student> (), exam ));
 
 

The output result is:

------ Before sort... tom: 74 jimy: 56 Mary: 92 every Y: 85 Jone: 56 BUSH: 52 Winter: 77 andyer: 63 LILY: 76 maryia: 89 ----- after sort .... jimy: 56 Jone: 56 BUSH: 52tom: 74 Mary: 92 127y: 85 Winter: 77 andyer: 63 LILY: 76 maryia: 89

Have you seen it? jimy, Jone, and Bush (no wonder the US president is stupid) fail. In addition, stable_partition is used, and the relative order between elements is not changed.

2 sort and container In STL, the standard containers mainly include vector, list, deque, String, set, Multiset, map, and multimay, where set, Multiset, map, multimap stores all its elements in a tree structure. For details, refer to: Learning STL map and STL set as the data structure basis. therefore, elements in these containers are always ordered.

The iterator types of these containers are not random iterators. Therefore, the sorting functions described above are unavailable for these containers. The above sort function is available for the following containers:

    • Vector
    • String
    • Deque

If the container you define also supports the random iterator, there is no problem in using the sorting algorithm.

For the list container, list comes with an sort member function list: Sort (). it is similar to sort in Algorithm functions, but list: sort is sorted Based on pointers. That is to say, all data movement and comparison are implemented using pointers, therefore, the sorted iterator remains valid (the iterator after sort in the vector will become invalid ).

 

3. select an appropriate sorting Function Why should we select a proper sorting function? Maybe you don't care about efficiency (the efficiency here refers to the program running time), or you have a small amount of data, so you don't think any function is important.

Otherwise, even if you don't care about efficiency, if you choose a proper sorting function, you will make your code easier to understand, and you will make your code more scalable, it is very important to gradually develop a good habit.

If you have used qsort in C language before and want to know the comparison between qsort and them, I will tell you that qsort and sort are the same, because they adopt fast sorting. In terms of efficiency, the following sort algorithms provide a sorting algorithm, with the efficiency increasing from high to low (the time consumed increases from small to large ):

    1. Partion
    2. Stable_partition
    3. Nth_element
    4. Partial_sort
    5. Sort
    6. Stable_sort

Remember, I have translated the article about objective STL before, which summarizes how to select a sort function:

    • To sort the vector, String, deque, or array containers in full order, you can select sort or stable_sort;
    • If you only need to obtain the top n elements in the vector, String, deque, or array container, partial_sort is the first choice.
    • For a vector, String, deque, or array container, you need to find the element at the nth position or you need to get the top N and it is not related to the internal order in Top N, nth_element is the most ideal;
    • If you want to separate elements that meet or do not meet a certain condition from the standard sequence container or array, you 'd better use partition or stable_partition;
    • If you use the list container, you can directly use the partition and stable_partition algorithms. You can use list: sort to replace sort and stable_sort to sort. If you want to obtain the sorting effect of partial_sort or nth_element, you must use it indirectly. As described above, you can choose from several methods.

Remember one sentence:If you want to save time, do not make detours, or take extra steps!

4. Summary The discussion of technology is like a bottomless pit, and it is often easy to extend from one point to countless other technical points. Therefore, we need to observe the problem from a global perspective, just like the sort algorithm in STL. In fact, there are also sorting algorithms such as make_heap and sort_heap in STL. This article does not mention. This article explains the characteristics of sorting algorithms in STL using examples, and summarizes how to select appropriate algorithms in actual situations.

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.