Mental model
Textbook sorts each have a weak spot. Merge sort always does about n log n comparisons, even on an array that is already sorted. Quicksort is fast on average but quadratic on unlucky inputs. Insertion sort is quadratic in general but unbeatable on tiny or nearly sorted arrays.
Library sorts are hybrids that combine the strengths and cover the weak spots:
- Timsort (Python, Java objects, also Android and V8): a merge sort that first looks for runs that are already sorted, uses insertion sort to build short runs, and merges cleverly.
- Introsort (.NET, the usual
std::sort): a quicksort that watches its own recursion depth and switches to heap sort before it can degrade, with insertion sort for small partitions. - Dual-pivot quicksort (Java primitives): quicksort with two pivots and three partitions, plus fallbacks.
The lab on this page is the plain top-down merge sort from the merge sort lesson. Keep it in mind as the baseline the hybrids improve on: run its Already sorted preset and notice that it still splits all the way down and merges every level, which is exactly the waste Timsort avoids. There is no Timsort or introsort code on this page; the descriptions below are conceptual and point to the real sources.
What each language runs
| Call | Algorithm (current implementation) | Stable | Worst case | Extra memory |
|---|---|---|---|---|
C# Array.Sort, List<T>.Sort, Span<T>.Sort |
introsort (documented) | no (documented) | O(n log n) | O(log n) |
C# Enumerable.OrderBy |
sorts extracted keys, original index as tie-breaker | yes | O(n log n) | O(n) |
Python list.sort, sorted |
Timsort; since 3.11 with the Powersort merge policy | yes (guaranteed) | O(n log n) | up to n/2 references |
Java Arrays.sort(Object[]), List.sort, Collections.sort |
TimSort (documented as an implementation note) | yes (guaranteed) | O(n log n) | up to n/2 references |
Java Arrays.sort(int[]) and other primitives |
dual-pivot quicksort (documented as an implementation note) | not applicable | O(n log n) (documented) | O(log n) typically |
C++ std::sort |
not specified; libstdc++ and libc++ use introsort variants | no | O(n log n) comparisons (required since C++11) | O(log n) |
C++ std::stable_sort |
not specified; typically merge sort with a temporary buffer | yes | O(n log n) with enough memory, O(n log² n) without | O(n) if available |
Two kinds of statements are mixed in that table, and the difference matters:
- Guarantees are in the specification or API contract: Python's and Java's object sorts are stable,
.NET's
Array.Sortis not, C++std::sortmakes O(n log n) comparisons andstd::stable_sortis stable. Code may rely on these. - Implementation notes describe the current algorithm: "TimSort", "dual-pivot quicksort", "introsort". Java's documentation explicitly labels these as notes that may change; C++ names no algorithm at all. Do not rely on, say, exact comparison counts.
Timsort, conceptually
Tim Peters designed it for CPython in 2002; his listsort.txt (in the references) is the authoritative
description. The ideas, in order:
1. Find natural runs. Scan from the left for a maximal run that is already ascending
(a[i] <= a[i+1]) or strictly descending (a[i] > a[i+1]). A strictly descending run is reversed in
place; strictness is what keeps the reversal stable, since equal elements are never inside one.
2. Extend short runs with binary insertion sort. If a natural run is shorter than minrun (chosen
between 32 and 64 so that n / minrun is close to a power of two), extend it to minrun elements with
binary insertion sort: insertion sort that finds the insertion point by binary search. Element moves
are still quadratic in the worst case, but on at most 64 elements a move is a short memmove, and
comparisons, which can be expensive for Python objects, drop to O(log minrun) each.
3. Merge runs on a stack, keeping them balanced. Each run is pushed onto a stack, and adjacent runs are merged when their lengths would otherwise become unbalanced. Balanced merges keep the total work at O(n log n) and the merge buffer small. The original rules had a subtle bug, found in 2015 by a formal verification effort, that could overflow the run stack on huge crafted inputs; it was fixed in CPython and Java. Since Python 3.11, CPython chooses merges with the Powersort policy (Munro and Wild), which gives provably near-optimal merge trees; the run detection and galloping are unchanged.
4. Merge with galloping. A merge copies the shorter run into a temporary buffer (at most n/2 elements) and merges back into the array. Normally it compares one element from each run at a time. If one run "wins" many times in a row (7 by default, adapted as it goes), the merge switches to galloping: it probes the winning run at offsets 1, 3, 7, 15, … (exponential search) to find how far the other run's next element reaches, then binary-searches inside that span and copies the whole block at once. When one run's elements mostly come before the other's, a block of k elements costs O(log k) comparisons instead of k. Galloping is the same doubling idea as exponential search in the searching module.
Result: O(n) comparisons on already sorted or reversed data, O(n log n) in the worst case, stable, and very few comparisons on real data with partial order (appended records, concatenated sorted lists). The memory cost is the merge buffer, up to n/2 elements.
Introsort, conceptually
David Musser's introsort (1997) starts as quicksort and keeps a depth budget, typically 2 ⌊log₂ n⌋:
introsort(range, depthLimit):
if size(range) <= 16: insertion sort; return # small: low overhead wins
if depthLimit == 0: heap sort the range; return # recursion is degenerating
p = choose pivot (e.g. median of three)
partition range around p
introsort(left part, depthLimit - 1)
introsort(right part, depthLimit - 1)
Balanced partitions never exhaust the budget, so typical inputs run at quicksort speed. An adversarial or unlucky input that keeps producing lopsided partitions hits the limit, and heap sort finishes that range in O(m log m). The whole sort is therefore O(n log n) worst case and in place, at the price of stability.
.NET's documentation spells out its version: insertion sort for partitions of at most 16 elements, heap
sort when the number of partitions exceeds 2 log n, quicksort otherwise. libstdc++'s std::sort stops
partitioning ranges below 16 elements and finishes the whole array with one insertion sort pass at the
end; libc++ uses a similar introsort with extra tuning. These thresholds are implementation details.
The quicksort lesson and the heap sort lesson cover the two halves of introsort, and insertion sort the third.
Dual-pivot quicksort (Java primitives)
Arrays.sort(int[]) and the other primitive overloads use the dual-pivot quicksort by Vladimir
Yaroslavskiy, Jon Bentley and Joshua Bloch, introduced in Java 7. Two pivots p ≤ q split the range into
three parts (< p, between, > q), which in practice reduces memory traffic compared with one pivot. The
current OpenJDK implementation also falls back to heap sort when recursion gets too deep, uses insertion
sort variants for small ranges, merges when it detects runs, and switches to counting sort for byte,
short and char arrays above a size threshold. The documentation promises O(n log n) on all data sets.
Why not Timsort for primitives too? Stability is invisible for primitives (two equal ints cannot be
told apart; -0.0/0.0 and NaN ordering for floating point are defined by the method), so a faster
unstable sort costs nothing. Objects need stability, and comparing them through compareTo is
expensive, which favours Timsort's low comparison count.
Choosing the right call
| Need | C# | Python | Java | C++ |
|---|---|---|---|---|
| Fast general sort | Array.Sort, List<T>.Sort |
list.sort |
Arrays.sort, List.sort |
std::sort |
| Guaranteed stable | OrderBy / ThenBy, or decorate with the index |
list.sort (always stable) |
List.sort, Arrays.sort(Object[]) |
std::stable_sort |
| Only the k smallest, in order | PriorityQueue or sort a copy |
heapq.nsmallest(k, a) |
PriorityQueue |
std::partial_sort |
| The k-th smallest only | (none built in) | (none built in) | (none built in) | std::nth_element, average O(n) |
| No allocation | Span<T>.Sort |
(not guaranteed) | primitives: Arrays.sort |
std::sort |
| Parallel | PLINQ AsParallel().OrderBy |
(none built in) | Arrays.parallelSort |
std::sort(std::execution::par, …) |
Whatever the call, the comparison must be a strict weak ordering: consistent, transitive, and never
"less" in both directions. Violating it is undefined behaviour for std::sort (it can read outside the
range), may throw "Comparison method violates its general contract" in Java's TimSort, and produces an
arbitrary order elsewhere. Subtraction comparators (return a - b) overflow for large ints; use
Integer.compare, a.CompareTo(b) or <.
Common mistakes
- Relying on stability from
Array.Sortorstd::sort. - Calling an implementation note a guarantee, for example "Java's sort is Timsort, so it is O(n) on sorted input" in an interview; the guarantee is O(n log n) and stability.
- Inconsistent comparators, including ones that use mutable state or random numbers.
- Sorting to find a minimum or the top k: O(n) and O(n log k) alternatives exist.
- Re-implementing sorts in production because a textbook sort looks simpler. The built-ins have years of tuning and adversarial testing behind them.
Edge cases
- Empty and single-element arrays: every built-in returns immediately.
- Already sorted input: Timsort does n − 1 comparisons; introsort still partitions (fast, but O(n log n)).
- Reverse-sorted input: Timsort reverses one descending run in O(n); a naive first-element-pivot quicksort would go quadratic, which is why real quicksorts choose pivots carefully and why introsort has its fallback.
- Many duplicates: three-way partitioning (Java's dual-pivot sort handles equal keys specially) avoids
quadratic behaviour on arrays like
[5, 5, 5, …].
Worked practice
1. A list of 10,000 log records sorted by time gets 50 new records appended, also in time order but interleaved with the old ones. Why does list.sort() handle this well?
Answer
There are two natural runs: the 10,000 old records and the 50 new ones. Timsort detects both in O(n) and performs one merge. Galloping copies long stretches of old records between consecutive new ones with O(log k) comparisons each, so the total is far below n log n comparisons.
2. Why does introsort switch to heap sort and not to merge sort when the depth limit is reached?
Answer
Heap sort is O(n log n) worst case and in place, so the whole algorithm keeps O(log n) extra space. Merge sort would need an O(n) buffer, and introsort is not stable anyway.
3. You must sort 1 million Person objects by last name, keeping people with the same last name in their current order. Which call do you use in each language?
Answer
C#: people.OrderBy(p => p.LastName) (stable), not List<T>.Sort. Python: people.sort(key=...).
Java: people.sort(Comparator.comparing(Person::lastName)). C++: std::stable_sort with a comparator on
last_name.
4. Why does Timsort reverse only strictly descending runs, not runs like [5, 4, 4, 3]?
Answer
Reversing [5, 4a, 4b, 3] would give [3, 4b, 4a, 5], swapping the two equal 4s and breaking
stability. With strictly descending runs there are no equal elements inside a run to swap.
Summary
- Built-in sorts are hybrids: Timsort (Python, Java objects) and introsort (.NET, typical
std::sort), plus dual-pivot quicksort for Java primitives. - Timsort finds natural runs, extends short ones with binary insertion sort, merges a balanced stack of runs (Powersort policy since Python 3.11) and gallops when one run dominates: stable, O(n) on sorted data, O(n log n) worst case, up to n/2 extra.
- Introsort is quicksort with a depth limit and a heap sort fallback, plus insertion sort for small ranges: in place, O(n log n) worst case, unstable.
- Rely on documented guarantees (stability, complexity), not on the current algorithm.
- Use
std::stable_sort,OrderBy, or Python's and Java's object sorts when equal elements must keep their order.