Sub topic 9
Timsort: Runs, Merges and Galloping
This chapter assumes you know how merge sort and insertion sort work, what a stable sort is, and how to read Big-O notation. Timsort is the stable sort behind Python's list.sort and sorted, Java's sort for object arrays, and V8's Array.prototype.sort. Tim Peters wrote it for Python in 2002. It is a merge sort that looks for order already present in the input and uses it.
The Working Model
Real data is often partly sorted. A log may be appended in time order, or a list may be sorted and then have a few items added at the end. Timsort splits the input into runs, which are stretches that are already in order. It then merges neighbouring runs until only one run is left.
Finding Runs
A run is either non-decreasing (a[i] <= a[i+1]) or strictly decreasing (a[i] > a[i+1]). Timsort reverses descending runs so that every run ends up ascending. The descending case has to be strict. If a descending run could contain equal elements, reversing it would swap them, and the sort would no longer be stable.
def find_runs(a):
runs = []
i, n = 0, len(a)
while i < n:
j = i + 1
if j < n and a[j] < a[i]:
while j < n and a[j] < a[j - 1]:
j += 1
runs.append(("desc", i, j))
else:
while j < n and a[j] >= a[j - 1]:
j += 1
runs.append(("asc", i, j))
i = j
return runs
print(find_runs([1, 2, 2, 5, 4, 3, 1, 7, 8]))
# [('asc', 0, 4), ('desc', 4, 7), ('asc', 7, 9)]On random data the natural runs are tiny. Timsort therefore sets a minimum run length, minrun, which is usually between 32 and 64. A shorter run is extended to minrun elements with binary insertion sort. Insertion sort is fast on small arrays and it is stable. Timsort picks minrun so that n / minrun is equal to, or slightly less than, a power of two. That keeps the later merges balanced.
def compute_minrun(n):
r = 0
while n >= 64:
r |= n & 1
n >>= 1
return n + r
print(compute_minrun(63), compute_minrun(64), compute_minrun(1000))
# 63 32 63Merging Runs
Timsort pushes each run onto a stack. It only ever merges two runs that sit next to each other in the array. If it merged runs that were not neighbours, an element could jump past an equal element that lies between them, and the sort would lose stability.
The stack follows rules that keep run lengths growing roughly like Fibonacci numbers. In the original version, with lengths A, B and C from the bottom up, the rules are A > B + C and B > C. When a rule breaks, Timsort merges B with whichever of its neighbours is smaller. This keeps the stack depth at O(log n) and stops it from merging a huge run with a tiny one over and over. Since Python 3.11, CPython chooses merges with the "powersort" policy instead. The runs and merges work the same way.
A merge copies only the shorter run into a temporary buffer. That is where the worst case of n/2 extra memory comes from.
Galloping
When one run keeps winning comparisons during a merge, comparing one element at a time is wasted work. After one side wins 7 times in a row (the starting MIN_GALLOP), Timsort switches to galloping mode. It checks positions 1, 3, 7, 15 and so on to find roughly where the next element from the other run belongs, then finds the exact spot with a binary search. The whole block is copied in one step.
If galloping stops paying off, Timsort goes back to the normal merge and raises the threshold. If it keeps paying off, Timsort lowers the threshold. Galloping uses the same < comparisons as the normal merge and takes from the left run whenever elements are equal, so it does not affect stability.
Common Errors
| Mistake | Consequence |
|---|---|
| Assuming Timsort is always O(n) | That is only the best case, already-sorted input. The worst case is O(n log n). |
| Assuming it sorts in place with O(1) memory | Merges need up to n/2 extra slots. |
| Giving it an inconsistent comparator | Java may throw `IllegalArgumentException: Comparison method violates its general contract!` |
Exercise
Why does Timsort reverse only strictly descending runs, and not runs like [5, 3, 3, 1]?
Show answer
Reversing [5, 3, 3, 1] would swap the two equal 3s and break stability. Because descending runs must be strict, Timsort stops at the second 3 and starts a new run there.
Exercise
The input [1..1000] is already sorted. How many comparisons does Timsort need, and why?
Show answer
It needs about n - 1 comparisons, which is O(n). The run scan finds one run covering the whole array, so no merges happen.