man rust/sorting
How Rust sorts: driftsort, ipnsort and select_nth_unstable
Rust slices have two sorts, sort and sort_unstable, each with _by and
_by_key variants, plus select_nth_unstable. Which algorithm runs behind
each one, what does “unstable” buy you, and why can a sort panic on a
comparison function that merely returns the wrong answers?
let mut pairs: Vec<(&str, usize)> = counts.into_iter().collect();
pairs.sort_unstable_by_key(|&(_, n)| std::cmp::Reverse(n));
This article reads library/core/src/slice/sort/ and library/alloc/src/slice.rs
at the 1.100.1 tag and checks them with small programs built with
rustc --edition 2024 -C opt-level=3 on an Apple M2 Pro. Every number below
comes from that source, the release notes, or one of those programs.
The short version
sort,sort_by,sort_by_key: driftsort, a stable hybrid of mergesort and quicksort, insort/stable/. It may allocate.sort_unstable*: ipnsort, an introsort (quicksort with a heapsort fallback), insort/unstable/. It never allocates.select_nth_unstable*: introselect built on ipnsort’s partition, with a median-of-medians fallback that keeps it O(n) in the worst case, insort/select.rs.
Both sorts are by Orson Peters and Lukas Bergdoll, and both arrived together
in Rust 1.81.0. The release note reads “Replace sort implementations with
stable driftsort and unstable ipnsort.”
Small slices: insertion sort up to 20
Both entry points start the same way
(stable/mod.rs L29-L86,
unstable/mod.rs L22-L58).
Zero-sized types and slices shorter than 2 return at once (“Instrumenting
the standard library showed that 90+% of the calls to sort by rustc are
either of size 0 or 1”). Up to MAX_LEN_ALWAYS_INSERTION_SORT = 20 elements,
both run a plain insertion sort, inlined at the call site. The comment
explains why. For a single sort call in general-purpose code, “the small
binary size of insertion sort is more important” than a faster small-sort
that would push other code out of the instruction cache. Anything longer
goes to driftsort_main or ipnsort, both marked #[inline(never)].
Insertion sort is not the cheapest in comparisons, and the boundary shows.
I counted comparisons with a closure that bumps a counter, on pseudo-random
u64s:
$ rustc --edition 2024 -C opt-level=3 sortcount.rs && ./sortcount
n = 20
sort_by 114 comparisons, 0 allocations, largest 0 bytes
sort_unstable_by 114 comparisons, 0 allocations, largest 0 bytes
...
n = 21
sort_by 83 comparisons, 0 allocations, largest 0 bytes
sort_unstable_by 92 comparisons, 0 allocations, largest 0 bytes
...
Twenty elements took 114 comparisons, and twenty-one took 83 with driftsort.
driftsort
drift::sort is described as “the hybrid top-level loop combining bottom-up
Mergesort with top-down Quicksort”
(drift.rs L1-L2).
It scans for runs that are already sorted, ascending or strictly descending,
and merges them in the order chosen by “powersort’s heuristic”. A run only
counts if it is long enough: min(len - len / 2, 64) for slices up to 4,096
elements and about the square root of the length beyond that
(L30-L43).
The comment says a single short run “will force on average several merge
operations”, so the bar is high. Stretches without a good run are left
unsorted. When an unsorted stretch meets a sorted run, or grows past the
scratch buffer, it is sorted by a stable quicksort that partitions through
the scratch buffer, and then merged
(L190-L216). So
random data is mostly quicksorted, and nearly sorted data is mostly merged.
The doc comment promises that “fully ascending and descending inputs will be
sorted with exactly N - 1 comparisons”
(L15-L16),
and the counter agrees:
n = 1000000, already sorted
sort_by 999999 comparisons, 1 allocations, largest 8000000 bytes
sort_unstable_by 999999 comparisons, 0 allocations, largest 0 bytes
n = 1000000, reversed
sort_by 999999 comparisons, 1 allocations, largest 8000000 bytes
sort_unstable_by 999999 comparisons, 0 allocations, largest 0 bytes
When the stable sort allocates
The same output shows a cost of stability. The stable sort allocated 8 MB
to sort a million already sorted u64s. driftsort_main sizes its scratch
buffer before looking at the data
(stable/mod.rs L94-L136):
const MAX_FULL_ALLOC_BYTES: usize = 8_000_000; // 8MB
let max_full_alloc = MAX_FULL_ALLOC_BYTES / size_of::<T>();
let len = v.len();
let alloc_len = cmp::max(
cmp::max(len - len / 2, cmp::min(len, max_full_alloc)),
SMALL_SORT_GENERAL_SCRATCH_LEN,
);
If that fits in a 4 KB buffer on the stack (AlignedStorage::<T, 4096>), no
heap allocation happens; otherwise it allocates alloc_len elements. So up
to 8 MB the buffer is as big as the slice. Between 8 and 16 MB it stays at
8 MB, and beyond that it is half the slice, which avoids “a sudden drop off”
in the comment’s words. The documentation says the same in words: “Short slices are handled
without allocation, medium sized slices allocate self.len() and beyond
that it clamps at self.len() / 2”
(slice.rs L100-L102).
A counting global allocator confirms each case for u64 (the last two calls
had no comparison counter):
n = 500
sort_by 4905 comparisons, 0 allocations, largest 0 bytes
n = 1000000
sort_by 20826347 comparisons, 1 allocations, largest 8000000 bytes
n = 1500000
sort_by 32114332 comparisons, 1 allocations, largest 8000000 bytes
n = 3000000
sort_by 67239649 comparisons, 1 allocations, largest 12000000 bytes
n = 10000000
sort 0 comparisons, 1 allocations, largest 40000000 bytes
sort_unstable 0 comparisons, 0 allocations, largest 0 bytes
500 u64s are exactly 4,000 bytes and fit on the stack. A million and a
half get a buffer of one million, three million get 1.5 million, and ten
million get five million.
ipnsort
ipnsort first looks for one run covering the whole slice
(unstable/mod.rs L114-L138).
If the slice is already sorted it returns; if it is strictly descending it
reverses it. Otherwise it runs quicksort with a budget of
2 * (len | 1).ilog2() imbalanced partitions. When that runs out, the
quicksort switches to heapsort, which bounds the worst case at O(n log n)
(quicksort.rs L18-L39).
Everything happens in place, which is why sort_unstable made no allocation
in any of the runs above. On a million random u64s it used 20.6 million
comparisons against driftsort’s 20.8 million.
“Unstable” means equal elements may change order. With 1,000 pairs
(i, i % 3) sorted by the second field:
let pairs: Vec<(usize, u32)> = (0..1000).map(|i| (i, (i % 3) as u32)).collect();
let mut a = pairs.clone();
a.sort_by_key(|&(_, key)| key);
let mut b = pairs.clone();
b.sort_unstable_by_key(|&(_, key)| key);
$ ./stable
sort_by_key: 0 3 6 9 12 15 18 21
sort_unstable_by_key: 564 999 3 6 9 12 15 18
Key functions
sort_by_key(f) is stable_sort(self, |a, b| f(a).lt(&f(b)))
(slice.rs L252):
the key function runs twice for every comparison. That is fine for a field
access and expensive for something like to_string().
sort_by_cached_key calls it once per element. Counting the calls on a
million random u64s:
$ ./keycalls
sort_by_key: 41652694 key calls
sort_by_cached_key: 1000000 key calls
sort_by_cached_key builds a Vec of
(key, index) pairs, sorts that with sort_unstable, and then moves the
elements into place
(L319-L330).
The result is still stable. The comment notes that the pairs “are unique, as
they are indexed, so any sort will be stable with respect to the original
slice”, and that sort_unstable is used “because it requires no memory
allocation”. When (K, u32) is smaller than (K, usize) and the slice is
short enough, the indexes are stored as u32 to save memory.
select_nth_unstable
select_nth_unstable(i) puts the element that belongs at index i there,
with nothing greater before it and nothing smaller after it, and returns the
three parts. select.rs calls it “an introselect algorithm based on ipnsort”,
with “Median of Medians using Tukey’s Ninther” as the fallback
(select.rs L1-L7).
partition_at_index has shortcuts for the two ends
(L34-L43).
Index len - 1 finds the maximum and swaps it to the end; index 0 does the
same with the minimum. Anything else runs the loop, which insertion-sorts any
part of 16 elements or fewer, partitions around a chosen pivot, and keeps
only the side holding the index. After 16 partitions it gives up on pivots
and calls median_of_medians
(L63-L93).
The comment explains why the limit is a constant. A limit of
ilog2(len) “like in sort would result in O(n log n) time complexity”.
n = 1000000
sort_unstable_by 20576868 comparisons, 0 allocations, largest 0 bytes
select_nth_unstable_by(n/2) 1996784 comparisons, 0 allocations, largest 0 bytes
select_nth_unstable_by(2) 1955283 comparisons, 0 allocations, largest 0 bytes
select_nth_unstable_by(0) 999999 comparisons, 0 allocations, largest 0 bytes
Finding the median or the third smallest of a million costs about two
comparisons per element, a tenth of a full sort. Index 0 is exactly n - 1.
The three smallest end up in v[..3] in no particular order; sort those
three if you need them ordered. A partial sort that does both,
partial_sort_unstable, exists on nightly only, behind the
slice_partial_sort_unstable feature (issue 149046).
When the comparison is wrong
Ord requires a total order. The old sorts would quietly return some order
when it wasn’t one. The 1.81.0 release notes warn that “the new
implementations have a good chance of detecting inconsistencies, throwing a
panic rather than returning knowingly unsorted data”. The panic lives in the
small-sort code, at the end of a merge whose two halves don’t run out
together
(smallsort.rs L839-L855).
A comparison that answers at random:
let mut x: u64 = 1;
let mut coin = move || {
x = x.wrapping_mul(6364136223846793005).wrapping_add(1);
if x >> 63 == 1 { Ordering::Less } else { Ordering::Greater }
};
let mut v: Vec<u64> = (0..1000).collect();
v.sort_by(|_, _| coin());
$ ./badord
thread 'main' (7639606) panicked at /rustc/20ddd01716a87c0fcf06ae4752d85a4abc15bcdf/library/core/src/slice/sort/shared/smallsort.rs:854:5:
user-provided comparison function does not correctly implement a total order
sort_unstable_by panicked the same way. The check is not a guarantee,
though. A comparison that returns Less for every pair of different values
claims both a < b and b < a, and sort_by returned without a panic on
1,000 such values. The documentation only says the sort “may panic”. The
comment above the panic admits that a strict weak ordering would be enough
for sorting, but the message says “total order” because that is what Ord’s
documentation asks for.
Curious facts
- Sorting 20 random elements took more comparisons (114) than sorting 21 (83), because 20 is the last length that always gets insertion sort.
sortallocated 8 MB to sort a millionu64s that were already sorted. It sizes its buffer before it looks for runs.sort_by_cached_keyis a stable sort built on the unstable one.select_nth_unstable(0)is a plain minimum: exactly n - 1 comparisons.sort_by_keycalls the key function twice per comparison: 41,652,694 times for a million randomu64s.
History
- Rust 1.15.0 (2017-02-02): “The standard sorting algorithm has been rewritten for dramatic performance improvements. It is a hybrid merge sort, drawing influences from Timsort. Previously it was a naive merge sort.”
- Rust 1.20.0 (2017-08-31):
sort_unstable,sort_unstable_byandsort_unstable_by_keyare stabilized. - Rust 1.34.0 (2019-04-11):
sort_by_cached_keyis stabilized. - Rust 1.49.0 (2020-12-31):
select_nth_unstableand its_byand_by_keyvariants are stabilized. - Rust 1.72.0 (2023-08-24): “Update runtime guarantee for
select_nth_unstable”. - Rust 1.81.0 (2024-09-05): driftsort and ipnsort replace the old
implementations, and sorts may panic on an inconsistent
Ord.
Sources
- rust-lang/rust at 1.100.1,
library/core/src/slice/sort/: stable/mod.rs L22-L136, stable/drift.rs L1-L43, unstable/mod.rs L15-L138, unstable/quicksort.rs L18-L39, select.rs L1-L93, shared/smallsort.rs L839-L855 - alloc/src/slice.rs L95-L102, L252, L319-L330
- core/src/slice/mod.rs, partial_sort_unstable L3321
- RELEASES.md at 1.100.1: 1.81.0 (L2696, L2749), 1.72.0 (L3823), 1.49.0 (L7080), 1.34.0 (L9070), 1.20.0 (L11073), 1.15.0 (L12042)
- driftsort and sort-research-rs, linked from the docs
grep -rl /lib/rust/sorting/
ls rust/
- draft How Rust's HashMap works: hashbrown, Swiss tables and SipHashWhat std's HashMap in Rust 1.100.1 does with a key: hashbrown's Swiss table with one control byte per slot, 8-byte groups on Apple silicon and 16 on x86, a 7/8 load factor, and SipHash-1-3 under keys that change per thread and per map.