STL Sort (reprint)

Source: Internet
Author: User

This article about the STL in the sort of writing is not deep, but it is very good.

1. Sort

The sort has two forms, the first of which has two iterator parameters, which form a pre-open-closed interval, sorted by the less relation of the elements, and the second form adds a predicate that specifies the collation. Sort is basically the most general sort function, it uses the fast sort algorithm , and in the recursive process, when the number of elements is less than a threshold (typically 16, my experiment is 24), it turns into a direct insert sort. The great mathematician Knuth has proved that, in the average sense, fast sequencing is the fastest; Of course, the worst complexity is poor. sort requires a random iterator , so for many compilers, using sort for a forward iterator (such as List) is a compilation error .

The basic way to use sort is as follows:

1#include <vector>2#include <algorithm>3#include <functional>4#include <cstdlib>5  6 using namespacestd;7  8 voidfunc1 ()9 {Tenvector<int>ar; One     //insert some random numbers into the array AGenerate_n (Back_inserter (AR), -, Rand); -     //sort by from small to large - sort (Ar.begin (), Ar.end ()); the}

Methods of reverse order

1 voidFunc2 ()2 {3vector<int>ar;4     //insert some random numbers into the array5Generate_n (Back_inserter (AR), -, Rand);6  7     //Method 1: Use a function as a predicate8 sort (Ar.begin (), Ar.end (), Greatethan);9     //Method 2: Use an affine function as a predicateTen     //Note that the following two methods need to have parentheses, in effect, to produce a temporary object One sort (Ar.begin (), Ar.end (), Compareint ()); A     //Method 3: Use predefined adapter, defined in <functional> -    sort (Ar.begin (), Ar.end (), greater<int> ()); -     //Method 4: Normal sort, then flip over the sort (Ar.begin (), Ar.end ()); - Reverse (Ar.begin (), Ar.end ()); -     //Method 5: Use the inverse iterator - sort (Ar.rbegin (), Ar.rend ()); +}

2, Stable_sort

sort advantages A lot, one drawback is that it's not a stable sort . What is the stability of sequencing? That is, if two elements are equal, they are ordered to remain in their original order after sorting (for example, we sort by the number of studies and then sort by grades,and then we hope the same grades are ranked in the order of the numbers). Unfortunately, the fast sorting algorithm is not stable, to pursue this, had to use Stable_sort.

In a variety of sorting algorithms, the merge sort is stable, but the general merge sort requires additional O (N) of storage space, which is not necessarily sufficient (perhaps more extravagant). So inside the Stable_sort, first determine if there is enough extra space (such as the CAP ()-size () section in VECOTR), and some use the normal merge function, the total time complexity and the quick ordering of an order of magnitude, all O (N*logn). If there is no additional space, a Merge_without_buffer key function is used for in-place merging (how to do this is quite tricky and can be specifically discussed), this merging process does not require additional storage space (except for the recursive stack). But the complexity of Time becomes O (N*logn), in which case the total stable_sort time complexity is O (N*LOGN*LOGN).

In short, the stable_sort is slightly slower, but can guarantee stability, using the same method and sort. But most of the time you can not use this method and this function, such as the above example, can be in the sorting comparison criteria to write scores and study number two conditions are OK.

classcstudent{ Public: Cstudent (); //Note that the const in this comparison function   bool operator< (const cstudent& RHS) Const {if (M_score! = Rhs.m_score) return (M_score &        Lt;rhs.m_score);    return M_name <rhs.m_name; }protected: std::stringM_name; intM_score;}; voidFunc4 () {vector<CStudent>Arstu; sort (Arstu.begin (), Arstu.end ());}

3, Heap_sort

Heap sorting is also a fast sorting algorithm, and the complexity is O (N*LOGN). There are some heap-related functions in the STL that can construct the heap, and if the root node is placed at the tail every time it is taken out on the constructed heap, all elements are cycled over and the final result is ordered. This is the sort_heap. The range of requirements for its use has been constructed in piles, such as:

1 voidFunc5 ()2 {3vector<int>ar;4     //Generate Data5Generate_n (Back_inserter (AR), -, Rand);6     //Construction Heap7 make_heap (Ar.begin (), Ar.end ());8     //Heap Sort9 sort_heap (Ar.begin (), Ar.end ());Ten}

4, List.sort

For list containers, it is not possible to use sort (including stable_sort) directly, from a technical point of view,sort requires a random iterator; from the point of view of the algorithm, thelist structure itself is not suitable for quick sorting. Therefore,a special sort algorithm is implemented inside the list container , which uses the merge sort and should be stable (indeterminate). such as:

1 list<int> li; 2     Li.sort ();

STL Sort (reprint)

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.