Sorting in Practice: Timsort to Powersort
Runs, adaptive merging and the sorts inside Python, Java, Rust and Go.
In 2015, researchers trying to prove Java's sort correct with a theorem prover discovered that it could crash: Timsort, the sort of Python since 2002 and of Java since 2011, did not maintain the invariant its merge rule was designed around. The first proof of its worst case came only in 2018, and Python 3.11 then replaced the merge rule with Powersort, whose merges are provably within of optimal.
What you’ll learn
- Model adaptive merge sorting with runs and merge costs, and state the lower bound for inputs with given run lengths.
- Describe Timsort's run detection, minrun, merge stack and galloping, and explain the 2015 invariant bug and the 2018 analysis.
- Compute Powersort's boundary powers and explain why its merge cost is .
- Name the sorts that Python, Java, C++, Go, Rust and JavaScript use (as of 2025), and explain why comparisons, memory traffic and branch mispredictions each matter.
Runs, and what merging them costs
Real inputs are rarely random permutations: logs appended in time order, a sorted list with a few new entries, the concatenation of sorted files. A run is a maximal stretch that is already ascending, or strictly descending, in which case it can be reversed in place without breaking stability. An input with runs of lengths can be sorted by merging adjacent runs only, a natural merge sort.
Merging runs of lengths and costs about in comparisons and moves. The merges form a binary merge tree whose leaves are the runs, in order, and the total cost is : every element is moved once per merge above its run.
Kraft. If run sits at depth of the merge tree, the leaf depths of this binary tree satisfy Kraft's inequality, exactly as in the lower-bound lesson:
Gibbs. Put and . The relative entropy is nonnegative whenever , so the cost per key is at least the entropy:
From entropy to runs. The entropy of probabilities is at most , with equality exactly when all runs are equally long. So a policy within of runs in time, and on one run, a sorted input, in :
A natural merge sort finds 8 sorted runs of 1,000 keys each and merges them in a perfectly balanced tree. How many element moves do all the merges make together?
Show the answer
24000
The balanced tree has levels, and each level moves all 8,000 keys once: . That is exactly with : for equal runs, balanced merging is optimal.
| Merge order for runs 5, 3, 3, 14, 1, 2 () | Merge cost |
|---|---|
| lower bound | 58.2 |
| best possible order of adjacent merges | 65 |
| Powersort | 67 |
| Timsort's classic rule (as repaired in 2015) | 73 |
Timsort: runs, minrun, a stack and galloping
Timsort (Tim Peters, 2002, for Python) is a natural merge sort engineered around real data:
- Scan left to right for the next run; reverse it if it is strictly descending.
- If the run is shorter than minrun, a length between 32 and 64 chosen from , extend it to minrun with binary insertion sort. Short pieces are cheap to insertion-sort, and equal-sized runs make balanced merges.
- Push the run on a stack and merge adjacent runs near the top while the stack's invariants fail. For the top three runs ( on top) they read and , so run lengths grow at least like Fibonacci numbers down the stack, the stack stays deep, and merged runs have similar sizes.
- Merge with galloping: once one run has won 7 times in a row (the initial MIN_GALLOP), switch to exponential search, probing offsets and then binary searching, to move a whole block of elements with comparisons; leave galloping when it stops paying, and adapt the threshold.
At the end, the stack is merged down to one run. Timsort is stable, makes comparisons on sorted input, and runs in time in the worst case.
def merge_collapse(runs, merge_at):
"""Timsort's merge rule, as repaired in 2015. runs: run lengths, top of stack last;
merge_at(i) merges runs[i] and runs[i + 1] into one entry."""
while len(runs) > 1:
n = len(runs) - 2
top3_bad = n > 0 and runs[n - 1] <= runs[n] + runs[n + 1]
top4_bad = n > 1 and runs[n - 2] <= runs[n - 1] + runs[n] # the 2015 fix
if top3_bad or top4_bad:
if runs[n - 1] < runs[n + 1]:
n -= 1
merge_at(n)
elif runs[n] <= runs[n + 1]:
merge_at(n)
else:
breakCalled after each push. Without the top4_bad test, the rule checks the invariants only among the top three runs, and a merge can break them one level deeper. Checked against a reference implementation of the merge order.
Even repaired, Timsort's rule is not entropy-optimal. Buss and Knop (2019) built inputs on which Timsort's merge cost is at least , while the best order never needs more than about , and proposed simpler policies, the -merge sorts, with better worst-case merge costs.
Timsort extends short runs with binary insertion sort, which still moves elements for a piece of length in the worst case. Why is that a good trade in Python?
- Binary insertion makes fewer moves than ordinary insertion sort
- Binary insertion is stable and ordinary insertion sort is not
- Comparisons are the expensive operation in Python, since each one calls the objects' comparison method, while moving references in a list is cheap; with , the moves stay few
- Binary insertion sort runs in time
Show the answer
C. Comparisons are the expensive operation in Python, since each one calls the objects' comparison method, while moving references in a list is cheap; with , the moves stay few
Binary search cuts comparisons to about per insertion, while the moves are the same as in ordinary insertion sort. In Python a comparison is a method call on two objects, far more expensive than shifting a pointer, and minrun caps the quadratic moves at a small constant per element.
Powersort: merging by power
Powersort (Munro & Wild, 2018) starts from the ideal: for equal runs, the best merge tree is perfectly balanced. Map the array onto , so that each run has a midpoint there. The power of the boundary between two adjacent runs is the first level of repeatedly halving at which their midpoints land in different pieces, the smallest with . A boundary of power 1 is the one a balanced tree would merge last; higher powers sit deeper and are merged earlier.
Powersort keeps Timsort's stack, but decides merges by powers alone. When a new run arrives, compute the power of its left boundary; while the boundary below the top of the stack has a power greater than , merge; then push. Each power takes time: it is determined by the highest bit in which the two midpoints, written as binary fractions, differ.
def power(s, n1, n2, n):
"""Power of the boundary between runs a[s : s+n1] and a[s+n1 : s+n1+n2] of an array of length n."""
a = 2 * s + n1 # twice the midpoint of the left run
b = a + n1 + n2 # twice the midpoint of the right run
p = 1
while (a << p) // (2 * n) == (b << p) // (2 * n): # same half at level p: look deeper
p += 1
return p
def powersort_cost(runs):
"""Total length merged when Powersort merges runs of these lengths."""
n, cost, stack = sum(runs), 0, []
s, l = 0, runs[0] # the newest run, not yet on the stack
for length in runs[1:]:
p = power(s, l, length, n)
while stack and stack[-1][2] > p: # the boundary below is deeper: merge it first
s0, l0, _ = stack.pop()
s, l = s0, l0 + l
cost += l
stack.append((s, l, p))
s, l = s + l, length
while stack:
s0, l0, _ = stack.pop()
s, l = s0, l0 + l
cost += l
return cost
print(powersort_cost([5, 3, 3, 14, 1, 2])) # 67
print(powersort_cost([4] * 8)) # 96: a perfectly balanced merge treeThis computes only the order and cost of the merges; a real implementation merges the runs of the array at the same moments. Checked against an independent implementation on thousands of run-length sequences.
Think first Eight runs of equal length have boundary powers from left to right. In what order does Powersort merge them?
Runs 1 and 2, then 3 and 4, then those two pairs (the power-2 boundary), then 5 and 6, 7 and 8, their pair, and finally the two halves across the power-1 boundary. That is the perfectly balanced tree, built from left to right as the runs arrive; each key is moved times, a merge cost of .
What your language runs, and what makes a sort fast
| Language | Call | Algorithm, as of 2025 | Stable |
|---|---|---|---|
| Python | list.sort, sorted | Timsort with Powersort's merge policy (since 3.11) | yes |
| Java | Arrays.sort on primitive arrays | dual-pivot quicksort (since Java 7) | not observable |
| Java | Arrays.sort on objects, List.sort | Timsort (since Java 7) | yes |
| C++ | std::sort | introsort in the major standard libraries | no |
| C++ | std::stable_sort | merge sort with a buffer; without one | yes |
| Go | sort.Sort, slices.Sort | pdqsort (since Go 1.19) | no |
| Rust | slice::sort / sort_unstable | driftsort / ipnsort (since Rust 1.81) | yes / no |
| JavaScript (V8) | Array.prototype.sort | Timsort (since V8 7.0, 2018) | yes, required since ES2019 |
Which of these is fastest depends on what the machine pays for:
- Comparisons dominate when comparing is expensive. Python calls a method for every comparison of two objects, so CPython's sort spends bookkeeping (binary insertion, galloping) to save comparisons.
- Memory traffic dominates for large arrays of small keys. Merging and partitioning scan memory sequentially, which caches and prefetchers reward, while heapsort's jumps from to miss the cache once the heap outgrows it. LaMarca and Ladner (1997) showed that tuning sorts for caches changes which one wins.
- Branch mispredictions dominate tight loops on random data. The outcome of
a[j] < pivotis a coin flip, so a processor that guesses branches is wrong about half the time. Kaligosi and Sanders (2006) found that a deliberately skewed pivot can make quicksort faster for this reason, and BlockQuicksort (Edelkamp & Weiß, 2016) removed the branch altogether.
That is why every fast sort is a hybrid: insertion sort below a small cutoff (Timsort's minrun of 32 to 64, around 16 to 24 elements in introsort and pdqsort), sorting networks for tiny fixed sizes in vectorized sorts, careful partitioning or merging for the rest, and a fallback that caps the worst case.
Key takeaways
- Real inputs have runs: sorting runs of lengths needs comparisons with , and a natural merge sort with a good merge policy achieves , that is .
- Timsort finds runs, extends short ones to minrun (32 to 64) by binary insertion, merges by stack invariants and gallops; its invariant bug (2015) and first worst-case proof (2018) show how subtle merge policies are.
- Powersort merges by the power of each run boundary, the level at which halving separates the runs' midpoints, and costs ; CPython uses it since 3.11.
- As of 2025: Python uses Timsort with Powersort merging; Java dual-pivot quicksort for primitives and Timsort for objects; C++ libraries introsort and a buffered merge sort; Go pdqsort; Rust driftsort and ipnsort; V8 Timsort.
- Speed depends on comparisons, memory traffic and branch mispredictions, and the best sorts are hybrids that use the cheapest tool at each scale.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
The input consists of 4 sorted runs of keys each. Up to lower-order terms, how many comparisons does an optimal adaptive sort need in the worst case?
Show the answer
C.
bits per key, so the bound is , and a balanced merge of the four runs (two levels, moves each) achieves it. The bound is about the runs, not about .
What did the 2015 attempt to verify OpenJDK's Timsort find?
- Timsort is not stable
- Timsort takes quadratic time on random input
- The merge rule checked its invariants only among the top three runs, so they could fail deeper in the stack; on inputs built for the purpose, the run stack outgrew its preallocated space and the sort crashed
- Galloping returns wrong positions for equal keys
Show the answer
C. The merge rule checked its invariants only among the top three runs, so they could fail deeper in the stack; on inputs built for the purpose, the run stack outgrew its preallocated space and the sort crashed
The invariants were meant to make run lengths grow like Fibonacci numbers down the stack, which bounds its depth; checking only the top three runs let a deeper triple violate them. Python repaired the rule by also checking the fourth run from the top, Java first by enlarging the stack.
Two adjacent runs have their midpoints at 0.30 and 0.40 of the array's length. What is the power of the boundary between them?
- 1
- 2
- 3
- 4
Show the answer
C. 3
Halve repeatedly. At level 1 both points lie in , at level 2 both in , and at level 3 the split at 0.375 separates them. The power is the first level that separates the midpoints: 3.
On random 32-bit integers, a quicksort whose partition loop has no data-dependent branches runs much faster than one that branches on each comparison, with the same number of comparisons. Why?
- On random data, "is a[j] < pivot?" is unpredictable, so the processor mispredicts about half of those branches and throws away work each time; branch-free code avoids the penalty
- Branch-free code makes fewer comparisons
- Branch-free code is stable
- The compiler deletes the comparisons from branch-free code
Show the answer
A. On random data, "is a[j] < pivot?" is unpredictable, so the processor mispredicts about half of those branches and throws away work each time; branch-free code avoids the penalty
Modern processors guess the outcome of each branch and run ahead; a wrong guess costs many cycles. On random keys the partition branch is a coin flip, which is why Edelkamp and Weiß's BlockQuicksort records the comparison outcomes in a buffer and swaps without branching.
Further reading
- T. Peters, "listsort.txt," notes in the CPython source tree (2002, revised since), on Timsort, galloping and the merge policy.
- S. de Gouw, J. Rot, F. S. de Boer, R. Bubel & R. Hähnle, "OpenJDK's java.utils.Collection.sort() is broken: the good, the bad and the worst case," CAV 2015, LNCS 9206.
- N. Auger, V. Jugé, C. Nicaud & C. Pivoteau, "On the worst-case complexity of TimSort," ESA 2018; arXiv:1805.08612.
- J. I. Munro & S. Wild, "Nearly-optimal mergesorts: fast, practical sorting methods that optimally adapt to existing runs," ESA 2018; arXiv:1805.04154.
- S. Buss & A. Knop, "Strategies for stable merge sorting," SODA 2019; arXiv:1801.04641.