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