How Timsort Works: The Sorting Algorithm Tim Peters Wrote for Python
Every time a Python program calls sorted(), a stretch of C inside Objects/listobject.c wakes up and goes looking for order that is already there. It usually finds some. The same idea, translated into Java, sorts objects in the JDK, and the Java version went into Android. A port in V8's Torque language has sorted JavaScript arrays in Chrome since version 70. Nobody sells it and almost nobody thinks about it. It carries a person's name, and the name is a joke.
"This describes an adaptive, stable, natural mergesort, modestly called timsort (hey, I earned it <wink>)." That is the first line of listsort.txt, the design note Tim Peters wrote for CPython in 2002, a document still being revised more than two decades later. On November 11, 2026, Guido van Rossum told the Python community on its discussion forum that Peters had died on July 15. He described Peters as a mentor and co-designer of the language, the author of the Zen of Python, and the man who wrote Timsort. Within hours the news was on the Hacker News front page. This is a guide to what he built, written from his own notes.
The bet: real data is not random
Sorting theory starts from a hard floor. A sort that only learns things by comparing two items needs about lg(n!) comparisons on average to put n items in order, where lg is log base 2. Averaged over every possible ordering, no comparison sort can do better. Quicksort, the textbook favourite, does roughly 39 percent more comparisons than that in Hoare's original random-pivot form, according to Peters' notes.
Peters bet on the averaging. The floor holds for an average over all permutations, but a real list is not a random permutation. It is a log file appended in time order, a table someone already sorted by surname and now wants by city, a sorted list with a few new records stuck on the end. "I believe that lists very often do have exploitable partial order in real life," he wrote, "and this is the strongest argument in favor of timsort."
He also set a price on the bet: on random data, where there is nothing to exploit, Timsort had to at least tie the heavily tuned samplesort hybrid it replaced, and it did a little better. His benchmark table for a random list of 1,048,576 items counts 19,606,028 comparisons for Timsort, against a theoretical floor of 19,458,756, less than one percent above the limit. On the same size list, sorted except for three random swaps, Timsort needed 1,048,958 comparisons, about one per element, where the old sort needed 19,838,588.
Runs, minrun and the insertion sort in the basement
The main loop is simple to state. Peters' summary: it "marches over the array once, left to right, alternately identifying the next run, then merging it into the previous runs 'intelligently'. Everything else is complication for speed."
A run is a stretch that is already in order, either ascending or descending. Descending runs get reversed in place, so everything downstream sees ascending data. A natural run can be any length. In random data most runs are short, two or three elements, which would make for many small, wasteful merges.
So Timsort sets a minimum. If a natural run is shorter than minrun, it is extended to that length with binary insertion sort (an insertion sort that uses binary search to find each item's slot). Textbooks call it pointless, because moving the items still costs quadratic time, but in CPython moving an item means copying a pointer, while a single comparison can run arbitrary Python code. When comparisons are the expensive part, it pays to cut them and accept more copying.
The value of minrun caused trouble for years. The original choice favoured powers of two, and the notes admit that the benchmark only tested powers of two, so "it took a long time to notice" the bad cases. A list of 2,112 items with minrun 32 ends in a lopsided merge of 2,048 items against 64. In 2025 Stefan Pochmann proposed letting minrun vary slightly from run to run. The number of runs is then always a power of two, and every pair of runs being merged differs in length by at most one element. The current note includes a driver that checks those claims for every list length up to two million.
Galloping, and knowing when to stop
Merging two sorted runs normally goes one item at a time. Compare the heads, take the smaller, repeat. Timsort also counts how many times in a row the same run has won. If one run wins seven times in a row (MIN_GALLOP is 7), the data is probably clumpy, and Timsort switches to galloping.
When galloping, Timsort takes the head of one run and searches the other run for its position. It checks positions 0, 1, 3, 7, 15 and so on, doubling each time, until it overshoots, then runs a binary search over the gap. A whole block then moves in one copy. When a long block belongs together, this needs about a logarithmic number of comparisons instead of a linear one.
Peters' notes are frank about where this loses. If the insertion point is at index 2, a plain linear scan needs 3 comparisons and galloping needs 4. "That's a huge loss! Really," he wrote, and the exclamation mark is his. Galloping only wins outright from index 6 onward, so the threshold adjusts itself: when galloping pays off, min_gallop drops, as low as 1 on data with many duplicates. When it fails, the threshold goes up by one. On random data it climbs high enough that galloping almost never starts.
The proof that broke it
Timsort keeps the runs it has not merged yet on a fixed-size stack. To keep that stack short, the original merge rule enforced an invariant that Peters later described as "loosely based on invariants involving the Fibonacci sequence": each run on the stack must be longer than the next two combined. That keeps run lengths growing at least as fast as Fibonacci numbers, so the stack stays small.
In 2015 Stijn de Gouw, Jurriaan Rot, Frank de Boer, Richard Bubel and Reiner Hähnle tried to prove the Java port correct with KeY, a semi-automatic theorem prover for Java. The proof would not go through. The merge routine checked the invariant only on the top three runs of the stack, and a merge could break it one level further down, where nothing was checking. The authors built an input to exploit the gap. With a worst-case array of 67,108,864 elements, Java's stack, declared with 40 slots, overflowed: java.lang.ArrayIndexOutOfBoundsException: 40. Their paper, presented at CAV 2015, gives a fix that checks the top four runs and proves it correct in KeY.
Python's response was quick and unexcited. Peters filed issue 23515, "Bad logic in timsort's merge_collapse", on February 24, 2015, and marked it low priority. CPython's stack was large enough that, in his words, "there's currently no machine in existence with enough memory to hold an array large enough for a contrived input." Benjamin Peterson committed the four-run check the next day. OpenJDK's current TimSort.java contains both repairs: the four-run check and a larger stack bound of 49, which a comment says covers arrays up to Integer.MAX_VALUE-4 in the worst case.
The bug also drew researchers to the merge rule itself. In September 2021 Peters replaced the Fibonacci rule with "powersort", from J. Ian Munro and Sebastian Wild. Powersort assigns each boundary between runs a depth in an idealised merge tree, using binary fractions of the run midpoints. Its merge cost is provably near-optimal relative to the entropy of the run lengths. It shipped in Python 3.11. The commit note is modest: most users "probably won't see a significant time difference". Peters' notes add one "curious factoid": of all the alternatives he had seen, powersort's rule is the only one that is always optimal for three runs.
- 2002TimsortTim Peters writes it for CPython's list.sort()
- 2011Java 7Joshua Bloch's port becomes the JDK's default sort for objects
- 2015-02The proof failsde Gouw et al. find the invariant bug with KeY; CPython patches it in a day
- 2018Chrome 70V8 makes Array.prototype.sort stable with a Torque port of Timsort
- 2021-09PowersortMunro and Wild's merge policy replaces the Fibonacci rule; ships in Python 3.11
- 2025Balanced minrunStefan Pochmann's scheme makes every merge as balanced as possible
- 2026-07-15Tim Peters diesAnnounced by Guido van Rossum on November 11
What is known, and what is not
Several things here can be checked. The design note is public, and its comparison counts come with the test harness that produced them. The Java bug has a published paper, a constructed input and a stack trace. The powersort change has a commit, an issue thread and a peer-reviewed paper behind it.
Other claims are weaker. Peters' speed comparisons against samplesort were measured on hardware from around 2002, and on one test pattern the results swung wildly between platforms, and of that, he wrote, "we don't have an explanation for it." The claim that real-world data usually contains exploitable order is a belief backed by experience, as he stated it himself. It is not a measured fact about all the data in the world. Proving that a sort is "correct" also depends on the specification. The 2015 KeY proof covered the repaired stack invariant and the absence of that crash, in the Java code with generics removed. It said nothing about what happens when a user passes a comparator that is not a consistent ordering. In that case Java throws "Comparison method violates its general contract!" or quietly returns a badly sorted array.
Read the note itself. It runs past 900 lines of plain text, with comparison tables, admissions of failure and a test driver at the bottom. It has a section titled "Galloping with a Broken Leg". It calls its own first merge rule "the first thing I made up that didn't obviously suck", then spends dozens of lines explaining a replacement he did not invent and adopted anyway, because two academics had a better one.
Sources
- listsort.txt, CPython design notes by Tim Peters
- In Memoriam: Tim Peters (1952–2026), Guido van Rossum, discuss.python.org
- de Gouw, Rot, de Boer, Bubel, Hähnle: "OpenJDK's java.utils.Collection.sort() is broken: The good, the bad and the worst case", CAV 2015 (PDF)
- OpenJDK TimSort.java
- CPython issue 23515, Tim Peters, February 2015
- CPython commit for issue 23515, February 25, 2015
- bpo-34561: Switch to Munro & Wild "powersort" merge strategy, September 2021
- Munro and Wild: "Nearly-Optimal Mergesorts", arXiv 1805.04154
- JDK-6804124: Replace modified mergesort in java.util.Arrays.sort with timsort
- V8 blog: Getting things sorted in V8