The principle of sort sorting algorithm in STL

Source: Internet
Author: User
Tags bool comparison sort
1, all sort algorithm introduction

All of the sort algorithm parameters need to be entered in a range,[Begin,end]. The iterator used here (iterator) needs to be a random iterator (Radomaccessiterator), that is, an iterator that can be randomly accessed, such as: It+n or something. (except partition and stable_partition)

If you need to define a comparison function yourself , you can pass the defined functor (functor) as a parameter . Each of these algorithms supports incoming comparison functions. The following is a list of the names of all STL sort algorithm functions:

          Function Name Functional description Sort           sorts all elements in a given interval
stable_sort    Stable ordering of all elements in a given interval
partial_sort    Sort all elements of a given interval
partial_sort_copy   copy and sort a given interval
nth_element    find the element corresponding to a position in a given interval
is_sorted      determine if an interval has been sequenced
partition      so that elements that meet a certain condition are placed in front
stable_partition    

Where nth_element is the most difficult to understand, in fact, This function is used to find out the first few . For example: To find the value of the middle number in an array of 7 elements, at which point I may not care about the front or the back, I only care what the value of the element in the fourth bit is. 2. Comparison function in sort

When you need to sort in a particular way, you need to specify a comparison function for sort, or the program will automatically provide a default comparison function (an imitation function).

A list of the profiling functions provided in the STL:

Name              function Description
equal_to           equal
not_equal_to unequal               less than
greater            greater than
less_equal        less than or equal to
greater_equal     

It is important to note that these functions are not all suitable for your sort algorithm, how to choose, and decide on your application. In addition, you cannot write the name of the functor directly, but instead write its overloaded () function:

Less<int> ()
greater<int> ()

These function templates can be used directly when the container element is a standard type (Int,float,char) or a string. But if you are defining your own type or need to sort it in other ways, there are two ways to achieve this: one is to write your own comparison function. The other is an overloaded type of ' < ' operation assignment.
Examples are as follows:

#include <iostream>
#include <algorithm>
using namespace std;

BOOL CMP (int x,int y)
{
    return x>y?true:false;
}

int main ()
{
    int arr[5] = {3,2,5,8,4};
    for (int i=0;i<5;i++)
    {
        cout<<arr[i]<< "  ";
    }
    cout<<endl;
    Sort (arr,arr+5); (1) Default from small to large sort
    //sort (arr,arr+5,cmp);//(2) Sort//sort (arr,arr+5,less<int> ()) with the CMP function of its own definition
    ;//(3) An imitation function provided by the STL. Pay attention to usage.
    sort (arr,arr+5,greater<int> ());//(4) An imitation function provided by the STL. Pay attention to usage. for
    (int i=0;i<5;i++)
    {
        cout<<arr[i]<< "  ";
    }
    cout<<endl;
    return 0;
}
3. Stability of Sort algorithm

You find it strange to have sort and stable_sort, and partition and Stable_partition. The difference is that a function with stable guarantees that the original relative order of the equal elements will remain unchanged after sorting. Perhaps you will ask, since equal, you also control his relative position, also can not know who is who. Here's a question to figure out, the equivalence here is that the function you provide means that two elements are equal, not necessarily identical elements.
For example, if you write a comparison function:

BOOL Less_len (const string &STR1, const string &str2)
{
        return str1.length () < Str2.length ();
}

At this point, "Apple" and "winter" are equal, if "apple" appears in front of "winter", with stable functions sorted, their order must be the same, if you use a function without "stable" sort, then after sorting, " Winter "may be in front of" Apple ". 4. Various sorting functions

4.1 Full order: Sort,stable_sort

A full order arranges all elements of a given range in the order of their size relationships. the functions for full ordering are: Sort and stable_sort.

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 1th, 3 forms, both sort and stable_sort do not specify a comparison function, and the system uses operator< to sort all elements within the interval [first,last] by default. 2nd, 4 forms, you can arbitrarily specify the comparison function, the application is more flexible.

sort uses a sophisticated "fast-sorting algorithm" (Most of the STL versions are now not simple and quick to sort, but with interpolation sorting algorithms). can guarantee a good average performance, the complexity of N*log (n), because the simple fast ordering in theory has the worst case, the performance is very low, its algorithm complexity is n*n, but most of the STL version has been optimized in this area, so you can rest assured that use.
Stable_sort uses a "merge sort", allocating enough memory to be N*log (n), otherwise its complexity is N*log (n) *log (n), which has the advantage of keeping the relative positions between equal elements consistent before and after sorting.

4.2 Local sorting

A local sort is actually a sort of order that is provided to reduce unnecessary operations . Its function prototypes are:Partial_sort and Partial_sort_copy.

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 the sort and stable_sort, it's easier to understand Partial_sort. Let's look at its purpose: There are 10 students in the class, and I want to know who is the 5 who have the lowest score . If you don't have a partial_sort, you need to sort all the people in order and then take the top 5. Now all you have to do is sort the minimum 5 names for the score:

Partial_sort (Vect.begin (), Vect.begin () +5, Vect.end (),less<student> ());

That's a good thing to know. When the amount of data is small may not see the advantage, if it is 1 million students, I want to find the lowest score of 5 people ...
Partial_sort uses a heap sort (heapsort), which in any case is N*log (n) in complexity. If you want to use Partial_sort to achieve full ordering, you just have to let the middle=last go.

Partial_sort_copy is actually a combination of copy and Partial_sort. the number of sorted (copied) is [first, last] and [Result_first, result_last) the smaller interval. If the [Result_first, Result_last] interval is greater than the [first, last] interval, then the partial_sort is equivalent to the combination of copy and sort.

4.3 nth_element specifying element ordering

Nth_element a sort that is easy to read but explains rather troublesome. It is more convenient to use examples:
There are 10 students in the class, and I want to know the students who are ranked in the bottom 4th place.
If you want to meet the above requirements, you can use sort order, and then take the 4th bit (because it is from the small to the big row), the more intelligent friends will use Partial_sort, only the top 4, and then get 4th place. In fact this is you or waste, because the first two bits you do not need to sort at all, at this time, you need nth_element:

Template <class randomaccessiterator>
void Nth_element (randomaccessiterator first, Randomaccessiterator Nth,
randomaccessiterator last);

Template <class Randomaccessiterator, class strictweakordering>
void Nth_element (randomaccessiterator First, Randomaccessiterator nth,
randomaccessiterator last, strictweakordering comp);

For the above instance requirements:

Nth_element (Vect.begin (), Vect.begin () +3, Vect.end (),less<student> ());

why is begin () +3 instead of +4? Begin () is the first, begin () +1 is the second, ... begin () +3 of course it's the fourth one.

In addition, partition and stable_partition, as if these two functions are not used for sorting, the ' classification ' algorithm, will be more appropriate. Partition is to divide the elements of an interval into two categories according to a certain condition. If you are using stable_partition, the relative order between the elements is unchanged.

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.