What algorithms are used in C++11 std::sort in different STL implementations?

前端 未结 2 1665
北恋
北恋 2020-12-12 23:57

The C++11 standard guarantees that std::sort has O(n logn) complexity in the worst case. This is different from the average-case

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 00:27

    Browsing the online sources for libstdc++ and libc++, one can see that both libraries use the full gamut of the well-known sorting algorithms from an intro-sort main loop:

    For std::sort, there is a helper routine for insertion_sort (an O(N^2) algorithm but with a good scaling constant to make it competitive for small sequences), plus some special casing for sub-sequences of 0, 1, 2, and 3 elements.

    For std::partial_sort, both libraries use a version of heap_sort (O(N log N) in general), because that method has a nice invariant that it keeps a sorted subsequence (it typically has a larger scaling constant to make it more expensive for full sorting).

    For std::nth_element, there is a helper routine for selection_sort (again an O(N^2) algorithm with a good sclaing constant to make it competitive for small sequences). For regular sorting insertion_sort usually dominates selection_sort, but for nth_element the invariant of having the smallest elements perfectly matches the behavior of selection_sort.

提交回复
热议问题