man cpp/sorting

std::sort, partial_sort and nth_element in libc++

lib / C++ 9 mindraft

checked against: libc++ 22.1.6, libstdc++ (GCC 15.2.0)

To get the three largest values out of a vector, C++ offers at least three standard calls: sort everything, partial_sort the first three, or nth_element around the third. The standard gives each a complexity, but only loosely. What does libc++ actually run, and which call is cheapest in practice?

I read LLVM’s libc++ at tag llvmorg-22.1.6, the version Apple clang 21 reports on my Mac (_LIBCPP_VERSION is 220106). Apple ships its own build, so I diffed the headers: sort.h, partial_sort.h, nth_element.h and stable_sort.h in the macOS SDK are identical to the upstream tag. One part I could not diff: std::sort on plain arithmetic types with the default comparator is compiled into the shared library (the extern template declarations in sort.h L834-858), and I only have Apple’s binary of that. For contrast I read GNU libstdc++ at releases/gcc-15.2.0, from source only; I have no libstdc++ toolchain to run it.

What the standard promises

From the current working draft (eel.is, generated 2026-08-23):

call[section]complexity
sort[sort]O(N log N) comparisons
partial_sort[partial.sort]approximately N · log(M) comparisons, M = middle − first
nth_element[alg.nth.element]“linear on average”
stable_sort[stable.sort]N log N comparisons with enough extra memory, otherwise N log² N

Note the word “average” for nth_element. Nothing bounds its worst case.

std::sort: introsort with pdqsort ideas

std::__introsort (sort.h L715-829) opens with a comment that describes it as introsort “combined with other ideas”, partly based on Orson Peters’ pattern-defeating quicksort. Each round of its loop does this:

  1. Ranges of 0 to 5 elements get fixed sorting networks (__sort3, __sort4, __sort5).
  2. Below 24 elements (__limit, L726) it finishes with insertion sort.
  3. If the depth budget is used up, it falls back to heapsort by calling __partial_sort(first, last, last) (L765-768). The budget is 2 · ⌊log₂ n⌋ (L867).
  4. Otherwise it picks a pivot: median of three, or above 128 elements (__ninther_threshold, L728) Tukey’s ninther, a median of three medians of three.
  5. If the pivot equals the element just left of the range, every element equal to it is moved left and skipped (__partition_with_equals_on_left, L655). This is the pdqsort trick that makes many equal keys cheap.
  6. It partitions. If the partition swapped nothing, it tries insertion sort on both halves, and gives up on a half after 8 moved elements (__insertion_sort_incomplete, L302-352). On already-sorted input this ends the sort early: 100,000 sorted ints took 200,006 comparisons, about 2n.
  7. It recurses into the left part and loops on the right.

Step 3 is what makes it an introsort. The heapsort fallback means O(n log n) comparisons whatever the input, which is what [sort] requires.

The branchless partition

For some types, step 6 uses __bitset_partition (L495), which the header comment calls “block quick sort” partitioning. It compares 64 elements against the pivot (__block_size, L61), stores the results as bits in a uint64_t, and then swaps the misplaced elements found by counting zero bits. The loop that compares has no data-dependent branches, so the CPU doesn’t mispredict on random data.

It is only switched on when __use_branchless_sort is true (L53-56): contiguous iterators, a cheap-to-copy arithmetic value type, and a comparator that is std::less or std::greater in disguise. Sorting a vector<int> with the default comparator goes through the copy compiled into the shared library, and in the upstream source of that copy (src/algorithm.cpp L14-28) the same test picks the bitset partition. Sorting a vector of pairs, or ints with your own lambda, doesn’t get it. With C++20’s std::ranges::sort, a projection wraps the comparator in a _ProjectedPred (make_projected.h L55-60), so a projected sort never gets it either. With the default identity projection the comparator is passed through untouched (L65-71), so that, in the words of the comment, “for certain algorithms, this would enable optimizations that rely on the type of the comparator”.

partial_sort: a heap of M

__partial_sort_impl (partial_sort.h L34-52) is short:

std::__make_heap<_AlgPolicy>(__first, __middle, __comp);
for (; __i != __last; ++__i) {
  if (__comp(*__i, *__first)) {
    _IterOps<_AlgPolicy>::iter_swap(__i, __first);
    std::__sift_down<_AlgPolicy, false>(__first, __comp, __len, 0);
  }
}
std::__sort_heap<_AlgPolicy>(std::move(__first), std::move(__middle), __comp);

It turns the first M elements into a heap whose top is the worst of the current best M. Every later element costs one comparison against that top, and only a winner costs a sift-down of log M steps. For M = 3 that is very close to one comparison per element. libstdc++ does the same: its __partial_sort calls __heap_select and then __sort_heap (stl_algo.h L1864-1871).

nth_element: quickselect with no safety net

__nth_element (nth_element.h L46-230) takes the median of the first, middle and last element as the pivot, partitions, and continues only into the side that holds position n. Ranges of 7 or fewer get a selection sort (__limit, L54). If a partition made no swaps, it checks whether the side it needs is already sorted, under a comment that reads “We were given a perfectly partitioned sequence. Coincidence?”

There is no depth counter and no fallback. libstdc++ has both: __introselect (stl_algo.h L1912-1937) gets a budget of 2 · log₂ n (L4768-4770), and when it runs out it switches to __heap_select, the same heap as partial_sort. So libstdc++’s worst case is O(n log n), and libc++’s is quadratic.

Counting comparisons

I counted comparisons for picking the three largest of 43,282 (key, value) pairs by value, with a counting comparator and a projection:

$ ./compares2     # 43,282 pairs, values 1..43282 shuffled
ranges::sort            754198 comparisons
ranges::partial_sort     43350 comparisons
ranges::nth_element      63657 comparisons

$ ./compares wide.txt   # 43,282 pairs, values between 1 and 10
k = 43282 distinct IDs
ranges::sort            143417 comparisons
ranges::partial_sort     43331 comparisons
ranges::nth_element     100038 comparisons

partial_sort with a heap of three makes about one comparison per element in both cases and beats nth_element, despite the “linear” label on the latter. Quickselect touches every element in the first partition, then a shrinking part in the next ones, so it makes a small multiple of n. Timed inside one process on the second set, best of 20: partial_sort 21 µs, nth_element 244 µs, full sort 266 µs.

The two ranges::sort lines also show pdqsort’s equal-key handling. With only ten distinct values, the full sort needs 143,417 comparisons instead of 754,198.

Making nth_element quadratic

M. D. McIlroy’s “A Killer Adversary for Quicksort” (1999) builds bad input on the fly. Every element starts as “gas”, a value larger than everything. When the algorithm compares two gas elements, the comparator freezes one of them to the next small value, choosing the one that is most likely the pivot. A comparison-based algorithm can’t tell this from real data. The frozen values are then a fixed input that you can replay. My version (killer gets the algorithm as a callable):

auto cmp = [&](int x, int y) {
    if (val[x] == gas && val[y] == gas) val[x == candidate ? x : y] = nsolid++;
    if (val[x] == gas) candidate = x;
    else if (val[y] == gas) candidate = y;
    return val[x] < val[y];
};

I ran it against std::nth_element(v.begin(), v.end() - 3, v.end()), which asks for the three largest, and against std::sort, then replayed each input with a plain counting comparator:

$ ./adversary_end
n=10000  nth_element: shuffled     25777, adversary   25024991   sort: shuffled   148355, adversary   387158
n=20000  nth_element: shuffled     32444, adversary  100049991   sort: shuffled   321019, adversary   838009
n=40000  nth_element: shuffled     54922, adversary  400099991   sort: shuffled   682013, adversary  1797710

Each doubling of n multiplies nth_element’s comparisons by 4, and 400,099,991 is about n²/4. std::sort also gets hurt, by a factor of 2.6, but stays close to n log n because its heapsort fallback kicks in. Asked for the three smallest (v.begin() + 2), the same adversary only got to 80,006 comparisons at n = 40,000, because it drives the pivots towards small values, which is the cheap side for that question.

Real data won’t look like this by accident. If an attacker can choose the values you select from, partial_sort is safe in both libraries, libstdc++’s nth_element should be by its source, and libc++’s nth_element is not.

stable_sort: sometimes a radix sort

std::stable_sort (stable_sort.h) allocates a buffer as large as the input when it can (L296-300). Up to 128 elements of a trivially copy-assignable type it uses insertion sort (__stable_sort_switch, L196-198). Above that it is a merge sort, with one exception added in LLVM 20: if the comparator is std::less in disguise and the values are integers, ranges of 1,024 to 65,536 elements (32,768 for 8-byte types) go to __radix_sort (L200-219, L248-262). LLVM 21 extended that to floating-point values.

The comparator type decides it, so a lambda that does the same thing switches it off:

$ ./stable    # random ints, best of 20
n=  50000  sort      807 us   stable_sort      143 us   stable_sort with a lambda     1573 us
n=1000000  sort    18939 us   stable_sort    11621 us   stable_sort with a lambda    42595 us

At 50,000 ints the stable sort is 5.6 times faster than std::sort, and 11 times faster than itself with [](int a, int b) { return a < b; }.

Making ties visible

std::sort, partial_sort and nth_element leave equal elements in an unspecified order, and code that happens to depend on that order passes its tests anyway. libc++ has a switch for this. With _LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY defined, __debug_randomize_range (__debug_utils/randomize_range.h) shuffles the range before sorting. The seed is the address of a static variable (shuffle.h L55-62), so address-space randomisation gives a new order on every run:

$ c++ -std=c++23 -O2 ties.cpp -o ties && ./ties && ./ties
bdfhjacegi
bdfhjacegi
$ c++ -std=c++23 -O2 -D_LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY ties.cpp -o ties_rand
$ ./ties_rand; ./ties_rand; ./ties_rand
bfhjdaiecg
bhfjdiaegc
bdhjfceaig

That’s ten letters with two distinct keys, sorted by key. Define _LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY_SEED to make the shuffle repeatable.

Curious facts

  • In a constant expression, libc++’s std::sort is pure heapsort: __sort_impl calls __partial_sort(first, last, last) when __libcpp_is_constant_evaluated() (sort.h L930-940).
  • std::sort on int* with the default comparator isn’t instantiated in your program. The header declares it extern template (L845), and nm -m on a program that sorts a vector<int> lists std::__1::__sort<std::__1::__less<int, int>&, int*> as “(undefined) external … (from libc++)”.
  • The heapsort used by partial_sort and the introsort fallback pops with Floyd’s “bottom-up” sift-down (pop_heap.h L47), which LLVM 15’s release notes say reduces the number of comparisons.
  • Sorting networks for 3, 4 and 5 elements exist in two versions in sort.h, branchless and branching, picked by the same __use_branchless_sort test (L99-212).

History

versionchangeevidence
1999McIlroy publishes the killer adversarySoftware: Practice and Experience, vol. 29
LLVM 14randomising unspecified orders in sort and nth_element (then via _LIBCPP_DEBUG=1)libc++ 14 release notes
LLVM 15pop_heap switches to bottom-up heapsortlibc++ 15 release notes
LLVM 16__bitset_partition appears in sort.habsent at llvmorg-15.0.0, present at llvmorg-16.0.0
LLVM 20stable_sort uses radix sort for integral typeslibc++ 20 release notes
LLVM 21radix sort for floating-point; constexpr stable sorting (P2562R1)libc++ 21 release notes

Sources

libc++ at llvmorg-22.1.6:

libstdc++ at releases/gcc-15.2.0:

Standard (working draft on eel.is): [sort], [partial.sort], [alg.nth.element], [stable.sort].

Papers: M. D. McIlroy, A Killer Adversary for Quicksort, Software: Practice and Experience, vol. 29, 1999. Orson Peters, pdqsort, linked from the sort.h comment.

ls cpp/