man python/sorting

How Python sorts: runs, galloping and powersort

lib / Python 11 mindraft

checked against: CPython 3.15.2

A common job: given a dict of counts, rank the IDs by how often they appear.

sorted(counts.items(), key=lambda item: item[1], reverse=True)
sorted(counts, key=counts.get, reverse=True)[:3]

Both lines end up in one C function, list_sort_impl in Objects/listobject.c. This article follows that function in CPython 3.15.2, using the source and its design notes in Objects/listsort.txt. Every number below comes from that source, a “What’s New” page, or a command I ran.

The short version

The algorithm is Tim Peters’s adaptive, stable mergesort (“timsort”). It walks the list once, left to right. It cuts the list into ascending runs, pads short runs to a minimum length with binary insertion sort, and pushes each run on a stack. A merge policy decides when adjacent runs on the stack get merged. Since 3.11 that policy is “powersort” by Munro and Wild. Merges switch into a “galloping” mode when one side keeps winning.

Step 1: find a run

count_run reads elements until the order breaks. An ascending run is non-decreasing. A descending run is non-increasing, and count_run reverses it in place so every run it returns is ascending.

Reversing a run with equal elements in it would swap them and break stability. For a long time the code avoided that by accepting only strictly descending runs. Since 3.13 it accepts non-increasing runs. It reverses each block of equal elements as it goes, and the final reversal of the whole run puts those blocks back in their original order. The same release added one more trick: after reversing a descending run, count_run keeps going if the next elements continue upward. The source comment gives [3, 2, 3, 4, 1] as an example, where the first four elements become one run.

The sort only ever calls <. Equality is deduced as “neither x < y nor y < x”.

Step 2: minrun and binary insertion sort

Random data has short runs. If a natural run is shorter than minrun, the main loop extends it to minrun elements with a stable binary insertion sort (binarysort). That function finds each insertion point with a binary search and then shifts pointers. Shifting is quadratic, but MAX_MINRUN is 64, so the pointers fit in L1 cache and comparisons dominate the cost.

If the list has fewer than 64 elements, minrun equals the length. The whole sort is then one binarysort call with no merging.

CPython 3.15 changed how minrun is chosen. Earlier versions picked one fixed value between 32 and 64. listsort.txt credits Stefan Pochmann (2025) with a scheme where minrun varies by one from run to run, so the number of runs is a power of 2 and every merge is between runs whose lengths differ by at most one. I ran the generator from listsort.txt (the MINRUN CODE note) for a few sizes:

n=50: 1 runs, lengths [50]
n=315: 8 runs, lengths [39, 40]
n=1000: 16 runs, lengths [62, 63]
n=32769: 1024 runs, lengths [32, 33]

For n=32769 the old rule used minrun=33 and produced 993 runs, which listsort.txt points out is not a power of 2. The effect on comparison counts is small. Averaged over 20 shuffles of 32769 distinct ints, 3.14.6 used 450582.8 comparisons and 3.15.2 used 450294.5. At n=32768 both versions gave the same 450281.5.

Step 3: the merge stack and powersort

Merging must only ever join two adjacent runs. Merging run A with run C first would move an element of C past an equal element in B. So the sort keeps a stack of pending runs and merges neighbours on it.

Up to 3.10, the policy kept two invariants on run lengths, checked in merge_collapse:

 * 1. len[-3] > len[-2] + len[-1]
 * 2. len[-2] > len[-1]

listsort.txt says these were hard to reason about and were not actually preserved. Researchers found that while working on a machine-checked correctness proof. In 3.11 the code switched to powersort.

Powersort gives each boundary between two adjacent runs a “power”: its depth in an ideal binary merge tree over the whole list. powerloop computes it from the midpoints of the two runs, scaled to the list length, by emulating binary division one bit at a time. When a new run arrives, found_new_run computes the power of the boundary between the top run and the new one. Then it merges runs on the stack while the saved power below the top is greater than the new power. The invariant is that powers on the stack strictly decrease, starting from the top. At the end, merge_force_collapse merges whatever is left.

The stack has MAX_MERGE_PENDING slots, defined as the number of bits in a size_t. That is 64 on a 64-bit build.

Step 4: merging and galloping

Merging two runs in place needs a temporary buffer the size of the shorter run. merge_lo copies run A out when A is shorter and merges left to right. merge_hi copies B and merges right to left.

Before either starts, merge_at does two searches. It finds where B[0] belongs in A, and elements of A before that point are already in place. It finds where A[-1] belongs in B, and elements of B after that are in place too. Both runs shrink before any copying happens.

The merge starts one pair at a time. It counts how many times in a row the winner comes from the same run. When the count reaches min_gallop (starting value MIN_GALLOP = 7), it switches to galloping. Galloping compares against positions 0, 1, 3, 7, 15 and so on, then finishes with a binary search, and moves the whole stretch in one copy. listsort.txt gives the cost: if the element belongs at index i, a linear scan needs i+1 comparisons and galloping needs 2*floor(lg(i))+2. Galloping only starts to win at i=6.

min_gallop adapts. Each pass of the gallop loop lowers it by one, never below 1. Leaving galloping mode raises it by one. On random data it climbs and galloping rarely triggers.

Two pre-sorted halves, with every element of the second half smaller than the first, show the effect. For 1000 elements the sort used 1026 comparisons on 3.15.2: about 1000 to find the two runs, and about 26 to merge them.

What it costs

I counted comparisons with a key class whose __lt__ increments a counter:

$ python3.15 count_compares.py 1000
Python 3.15.2  n=1000  lg(n!)=8529
  ascending         999
  descending        999
  all equal         999
  random           8662
  two blocks       1026
  interleaved      1999

Sorted, strictly reversed and all-equal input each take n-1 comparisons. listsort.txt gives the same lower figure. Random input took 8662 comparisons, 1.6% above lg(n!), the information-theoretic average lower bound for any comparison sort. The “interleaved” case is the evens followed by the odds: two runs whose merge alternates, so galloping has nothing to skip.

3.9.6 and 3.12.16 gave identical counts on every row, though powersort arrived between them. 3.13.3 and 3.14.6 gave 8665 for random, and 3.15.2 gave 8662. I did not trace which change moved those numbers.

The worst case is O(n log n) comparisons. That bound comes from the Munro and Wild paper that listsort.txt cites for powersort. I did not check it against the code.

Extra memory is at most n/2 pointers for the merge buffer. tracemalloc agrees on 3.15.2: sorting a list of 1,000,000 shuffled ints peaked at 4,000,000 bytes (500,000 eight-byte pointers). The same list already sorted peaked at 0 bytes. A merge that needs at most 256 temp slots (128 with a key function) uses a buffer inside the on-stack MergeState and never calls malloc.

key=, reverse= and sorted()

With key=, the sort calls the key function exactly once per element before sorting. A counting key on 1000 items was called 1000 times. The results go in a separate keys array, and the sort moves keys and values in lockstep. For lists under 128 items that array lives in the unused part of that on-stack buffer. Larger lists get a malloc. A key sort therefore needs n pointers for the keys plus up to n/2 each for the key and value halves of the merge buffer. Sorting 1,000,000 shuffled ints with an identity key peaked at 16,000,000 bytes, which is 2n pointers.

reverse=True is two reversals. The code reverses the list, runs the normal stable sort, and reverses the result. Reversing first means equal elements end up in their original order after the second reversal. On 3.15.2:

>>> counts = {"b": 2, "a": 3, "c": 2, "d": 2}
>>> sorted(counts, key=counts.get, reverse=True)
['a', 'b', 'c', 'd']
>>> list(reversed(sorted(counts, key=counts.get)))
['a', 'd', 'c', 'b']

A side effect: with reverse=True, both ascending and descending input took 999 comparisons for n=1000.

sorted() is short. builtin_sorted builds a new list from the iterable with PySequence_List, looks up that list’s sort method, and calls it with the same arguments. The copy is the only extra work.

During the sort, the list is empty. list_sort_impl saves the item array and sets the list’s size to 0, so a comparison that touches the list cannot corrupt memory. A __lt__ that checks len() on the list being sorted sees 0. A __lt__ that appends to it gets ValueError: list modified during sort.

Type-specialised comparisons

A generic comparison goes through PyObject_RichCompareBool, which dispatches on both types every time. Since 3.7, list_sort_impl first scans all keys. It takes the type of the first key and checks that every key has the same type. It then picks a compare function:

  • unsafe_latin_compare for str keys that all use one byte per character: a memcmp.
  • unsafe_long_compare for int keys that are all “compact”, which means one internal digit. With 30-bit digits that covers absolute values below 2**30.
  • unsafe_float_compare for float keys: a C double comparison.
  • unsafe_object_compare for any other single type: the type’s own rich compare, called directly.
  • unsafe_tuple_compare when every key is a non-empty tuple. The check above runs on the tuples’ first elements.
  • safe_object_compare for mixed types.

Timing sorted() on 200,000 values with the same order but different types shows the cost of falling off a fast path (Python 3.15.2, Apple M2 Pro, best of 5):

  small ints (< 2**30)            22.9 ms
  big ints (>= 2**30)             41.1 ms
  floats                          22.7 ms
  ints, one float at the end      47.7 ms
  latin-1 strings                 34.5 ms
  non-latin strings               54.7 ms

One float among 200,000 ints moves the whole sort to the generic path and makes it about twice as slow.

Back to ranking counts

Both lines from the start of this article sort with a key, so the type check runs on the keys. Those are the counts, all small ints, and every comparison is unsafe_long_compare. The first line sorts (id, count) tuples, but its key returns item[1], so tuple comparison never happens.

For k distinct IDs the sort is O(k log k). Keeping 3 of them needs one pass. heapq.nlargest(3, ...) keeps a 3-item heap and compares each new key against the smallest of the three. Counter.most_common(n) calls nlargest, and most_common() with no argument calls sorted(..., reverse=True). nlargest returned the same 3 IDs in the same order as the slice in every run, ties included. I measured both on dicts of random counts (Python 3.15.2, Apple M2 Pro):

  k=     50: compares sort=      220 nlargest=     73   time sort=      2.1 us  nlargest=      3.0 us
  k=   1000: compares sort=     8683 nlargest=   1029   time sort=     70.0 us  nlargest=     31.2 us
  k= 100000: compares sort=  1531800 nlargest= 100050   time sort=  14064.8 us  nlargest=   3233.9 us

At 50 IDs the full sort is faster despite three times the comparisons. That sort is a single binarysort with its keys in the on-stack buffer, so it never calls malloc. At 1000 IDs nlargest is about twice as fast, and at 100,000 about four times. For a few hundred distinct IDs, either line is fine.

Curious facts

  • Sorting a list of tuples calls __eq__ before __lt__. unsafe_tuple_compare looks for the first unequal position with ==. On 3.15.2, sorting 100 objects took 531 __lt__ calls and no __eq__ calls. The same objects wrapped in 1-tuples took 531 of each.
  • The first merge policy’s invariants turned out not to hold, a bug found by researchers trying to complete a machine-checked correctness proof. The design notes say it was easy to repair, but the discovery set off research into better merge policies, and powersort, which CPython uses since 3.11, came out of that work.
  • On 3.9.6 and 3.12.16 the comparison counts in the table above are identical, even though the merge policy changed to powersort between them.
  • listsort.txt calls powersort the only policy its author found that is always optimal for three runs: merge the shorter of the outer two with the middle one first.
  • A list shorter than 64 items is sorted by binary insertion sort alone.

Version history

  • 2.3: list.sort() “extensively rewritten by Tim Peters” (What’s New 2.3). MIN_GALLOP is in the v2.3.7 source and absent from v2.2.3.
  • 2.4: key and reverse parameters, the sorted() builtin, and a guarantee that sorting is stable (What’s New 2.4).
  • 3.0: cmp removed. key and reverse became keyword-only (What’s New 3.0).
  • 3.2: functools.cmp_to_key() added. Key sorts store keys and values in two parallel arrays instead of wrapping every element (bpo-9915, What’s New 3.2).
  • 3.7: type-specialised compares, “up to 40-75% faster” for common cases (bpo-28685, What’s New 3.7).
  • 3.11: powersort merge policy. powerloop is in v3.11.0 and absent from v3.10.0. What’s New 3.11 does not mention it.
  • 3.13: non-strict descending runs and run extension after reversal (present in v3.13.0, absent from v3.12.0).
  • 3.15: Pochmann’s varying minrun (minrun_next present in v3.15.0, absent from v3.14.0).

Sources

ls python/