Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 O(nlog⁡n)O(n \log n) worst case came only in 2018, and Python 3.11 then replaced the merge rule with Powersort, whose merges are provably within O(n)O(n) of optimal.

What you’ll learn

  • Model adaptive merge sorting with runs and merge costs, and state the lower bound nH−O(n)nH - O(n) 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 nH+O(n)nH + O(n).
  • 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 ρ\rho runs of lengths r1,…,rρr_1, \dots, r_\rho can be sorted by merging adjacent runs only, a natural merge sort.

Merging runs of lengths aa and bb costs about a+ba + b in comparisons and moves. The merges form a binary merge tree whose leaves are the runs, in order, and the total cost is ∑iri⋅depthi\sum_i r_i \cdot \mathrm{depth}_i: every element is moved once per merge above its run.

DerivationEvery merge tree costs at least nH
  1. ∑i2−di  ≤  1\sum_i 2^{-d_i} \;\le\; 1

    Kraft. If run ii sits at depth did_i of the merge tree, the leaf depths of this binary tree satisfy Kraft's inequality, exactly as in the lower-bound lesson:

  2. costn  =  ∑ipi di  =  −∑ipilog⁡2qi  ≥  −∑ipilog⁡2pi  =  H\frac{\text{cost}}{n} \;=\; \sum_i p_i\, d_i \;=\; -\sum_i p_i \log_2 q_i \;\ge\; -\sum_i p_i \log_2 p_i \;=\; H

    Gibbs. Put pi=ri/np_i = r_i / n and qi=2−diq_i = 2^{-d_i}. The relative entropy ∑ipilog⁡2(pi/qi)\sum_i p_i \log_2 (p_i / q_i) is nonnegative whenever ∑iqi≤1\sum_i q_i \le 1, so the cost per key is at least the entropy:

  3. nH+O(n)  ≤  nlog⁡2ρ+O(n)nH + O(n) \;\le\; n \log_2 \rho + O(n)

    From entropy to runs. The entropy of ρ\rho probabilities is at most log⁡2ρ\log_2 \rho, with equality exactly when all runs are equally long. So a policy within O(n)O(n) of nHnH runs in O(n+nlog⁡ρ)O(n + n \log \rho) time, and on one run, a sorted input, in O(n)O(n):

Predict before you look

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 log⁡28=3\log_2 8 = 3 levels, and each level moves all 8,000 keys once: 3×8,000=24,0003 \times 8{,}000 = 24{,}000. That is exactly nHnH with H=log⁡28=3H = \log_2 8 = 3: for equal runs, balanced merging is optimal.

Merge order for runs 5, 3, 3, 14, 1, 2 (n=28n = 28)Merge cost
lower bound nHnH58.2
best possible order of adjacent merges65
Powersort67
Timsort's classic rule (as repaired in 2015)73
Computed by brute force over all merge trees and by implementations of both policies. Across thousands of random run-length sequences, Powersort stayed within 2n2n of nHnH, while Timsort's rule reached 1.47 times the optimal cost.

Timsort: runs, minrun, a stack and galloping

Timsort (Tim Peters, 2002, for Python) is a natural merge sort engineered around real data:

  1. Scan left to right for the next run; reverse it if it is strictly descending.
  2. If the run is shorter than minrun, a length between 32 and 64 chosen from nn, extend it to minrun with binary insertion sort. Short pieces are cheap to insertion-sort, and equal-sized runs make balanced merges.
  3. Push the run on a stack and merge adjacent runs near the top while the stack's invariants fail. For the top three runs X,Y,ZX, Y, Z (ZZ on top) they read ∣X∣>∣Y∣+∣Z∣|X| > |Y| + |Z| and ∣Y∣>∣Z∣|Y| > |Z|, so run lengths grow at least like Fibonacci numbers down the stack, the stack stays O(log⁡n)O(\log n) deep, and merged runs have similar sizes.
  4. Merge with galloping: once one run has won 7 times in a row (the initial MIN_GALLOP), switch to exponential search, probing offsets 1,3,7,…,2j−11, 3, 7, \dots, 2^j - 1 and then binary searching, to move a whole block of kk elements with O(log⁡k)O(\log k) 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 n−1n - 1 comparisons on sorted input, and runs in O(nlog⁡n)O(n \log n) time in the worst case.

python
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:
            break

Called 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 (1.5−o(1)) nlog⁡2n(1.5 - o(1))\, n \log_2 n, while the best order never needs more than about nlog⁡2nn \log_2 n, and proposed simpler policies, the α\alpha-merge sorts, with better worst-case merge costs.

Check your understanding

Timsort extends short runs with binary insertion sort, which still moves Θ(m2)\Theta(m^2) elements for a piece of length mm in the worst case. Why is that a good trade in Python?

  1. Binary insertion makes fewer moves than ordinary insertion sort
  2. Binary insertion is stable and ordinary insertion sort is not
  3. Comparisons are the expensive operation in Python, since each one calls the objects' comparison method, while moving references in a list is cheap; with m≤64m \le 64, the moves stay few
  4. Binary insertion sort runs in O(mlog⁡m)O(m \log m) 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 m≤64m \le 64, the moves stay few

Binary search cuts comparisons to about log⁡2m\log_2 m 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 [0,1)[0, 1), so that each run has a midpoint there. The power of the boundary between two adjacent runs is the first level ℓ\ell of repeatedly halving [0,1)[0, 1) at which their midpoints land in different pieces, the smallest ℓ\ell with ⌊x⋅2ℓ⌋≠⌊y⋅2ℓ⌋\lfloor x \cdot 2^\ell \rfloor \ne \lfloor y \cdot 2^\ell \rfloor. 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 pp of its left boundary; while the boundary below the top of the stack has a power greater than pp, merge; then push. Each power takes O(1)O(1) time: it is determined by the highest bit in which the two midpoints, written as binary fractions, differ.

python
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 tree

This 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 3,2,3,1,3,2,33, 2, 3, 1, 3, 2, 3 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 log⁡28=3\log_2 8 = 3 times, a merge cost of 3n=nH3n = nH.

What your language runs, and what makes a sort fast

LanguageCallAlgorithm, as of 2025Stable
Pythonlist.sort, sortedTimsort with Powersort's merge policy (since 3.11)yes
JavaArrays.sort on primitive arraysdual-pivot quicksort (since Java 7)not observable
JavaArrays.sort on objects, List.sortTimsort (since Java 7)yes
C++std::sortintrosort in the major standard librariesno
C++std::stable_sortmerge sort with a buffer; O(nlog⁡2n)O(n \log^2 n) without oneyes
Gosort.Sort, slices.Sortpdqsort (since Go 1.19)no
Rustslice::sort / sort_unstabledriftsort / ipnsort (since Rust 1.81)yes / no
JavaScript (V8)Array.prototype.sortTimsort (since V8 7.0, 2018)yes, required since ES2019
Library internals change between versions; check the documentation of the version you use. Equal primitive values are indistinguishable, so stability does not matter for them.

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 ii to 2i+12i + 1 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] < pivot is 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 rir_i needs nH−O(n)nH - O(n) comparisons with H≤log⁡2ρH \le \log_2 \rho, and a natural merge sort with a good merge policy achieves nH+O(n)nH + O(n), that is O(n+nlog⁡ρ)O(n + n \log \rho).
  • 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 [0,1)[0, 1) separates the runs' midpoints, and costs nH+O(n)nH + O(n); 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.

Question 1

The input consists of 4 sorted runs of n/4n/4 keys each. Up to lower-order terms, how many comparisons does an optimal adaptive sort need in the worst case?

  1. n/4n/4
  2. nlog⁡2nn \log_2 n
  3. 2n2n
  4. 4n4n
Show the answer

C. 2n2n

H=log⁡24=2H = \log_2 4 = 2 bits per key, so the bound is nH=2nnH = 2n, and a balanced merge of the four runs (two levels, nn moves each) achieves it. The bound is about the runs, not about nlog⁡2nn \log_2 n.

Question 2

What did the 2015 attempt to verify OpenJDK's Timsort find?

  1. Timsort is not stable
  2. Timsort takes quadratic time on random input
  3. 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
  4. 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.

Question 3

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. 1
  2. 2
  3. 3
  4. 4
Show the answer

C. 3

Halve [0,1)[0, 1) repeatedly. At level 1 both points lie in [0,0.5)[0, 0.5), at level 2 both in [0.25,0.5)[0.25, 0.5), and at level 3 the split at 0.375 separates them. The power is the first level that separates the midpoints: 3.

Question 4

On 10810^8 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?

  1. 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
  2. Branch-free code makes fewer comparisons
  3. Branch-free code is stable
  4. 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.