Sub topic 9
Timsort: Runs, Merges and Galloping
This chapter assumes you already know how merge sort and binary search work, and that you know the definition of a stable sort from earlier chapters. You should also be able to read Python that uses slices and the bisect module.
Tim Peters wrote Timsort for CPython in 2002. It became the sort behind Python's sorted and list.sort. Java's Arrays.sort for object arrays and List.sort use it as of JDK 7, and V8 (the JavaScript engine in Chrome and Node.js) has used it since version 7.0. Timsort is a merge sort that adapts to its input. It looks for order that already exists in the data and spends work only where the data is out of order. On random input it takes O(n log n) comparisons. On input that is already sorted, or sorted in reverse, it takes n − 1 comparisons.
The Three Ideas
Timsort combines three techniques:
- Natural runs. It scans the input for stretches that are already sorted, so it does not split the array blindly the way textbook merge sort does.
- A merge policy. It keeps found runs on a stack and merges neighbours according to size rules, so merges stay balanced.
- Galloping. When one run keeps "winning" during a merge, it stops comparing elements one at a time and jumps ahead with an exponential search.
Every step keeps the sort stable. The sections below show the constraint behind each step.
Finding Runs
A run starts at the current position. It is either non-descending (a[0] <= a[1] <= ...) or strictly descending (a[0] > a[1] > ...). A descending run is reversed in place, which turns it into an ascending run.
The asymmetry matters. If Timsort reversed a run like 3, 2, 2, 1, the two equal 2s would swap places, and the sort would no longer be stable. Because descending runs must be strict, a run never contains equal elements, so reversing it cannot reorder equal elements.
Minrun
Random data has very short natural runs, often of length 2. Merging thousands of tiny runs costs a lot, so Timsort sets a minimum run length called minrun. If a natural run is shorter, Timsort extends it to minrun elements with binary insertion sort. Binary insertion sort finds each element's slot by binary search and then shifts the elements after it. It is fast on small arrays, and it is stable if the search uses bisect_right, which places a new element after any equal ones.
Minrun falls between 32 and 64. Timsort chooses it so that n / minrun is a power of two or slightly less than one. With that choice, the final merges join runs of similar size. A value such as n / minrun = 2^k + 1 would leave one small run that has to be merged into a very large one at the end.
The Run Stack and Merge Policy
Each run is pushed onto a stack as a (start, length) pair. Timsort merges only adjacent runs. If it merged two runs that were not next to each other, an element from the later run could end up ahead of an equal element from an earlier run, which breaks stability.
Call the top three run lengths A, B and C, with C on top. The original rules required these invariants:
- A > B + C
- B > C
When a rule fails, Timsort merges B with whichever neighbour is smaller. The invariants make run lengths grow at least as fast as the Fibonacci numbers, so the stack stays O(log n) deep and merges stay balanced.
Merging with Less Memory
To merge adjacent runs X and Y, Timsort first trims elements that are already in their final place:
- Elements at the start of X that are ≤ Y's first element are already correct.
- Elements at the end of Y that are ≥ X's last element are already correct.
Next it copies the shorter of the two remaining pieces into a temporary buffer. If X is shorter, it merges left to right ("mergelo"). If Y is shorter, it merges right to left ("mergehi"). Either way the buffer holds at most n/2 elements. Ties always go to the element from X, the left run, which keeps the merge stable.
Galloping
In ordinary merging, one comparison moves one element. Suppose X's elements are all smaller than most of Y's. Then X wins comparison after comparison. After one run has won MIN_GALLOP times in a row (the starting value is 7), Timsort switches to galloping mode. It probes positions 1, 3, 7, 15, … ahead until it overshoots, then runs a binary search in the last gap. This finds the length of a block in O(log k) comparisons instead of k, and the whole block is copied at once.
Galloping must also handle ties in a stable way:
- To find how many elements of X go before Y's current element y, use gallop_right. It counts elements ≤ y, so X's equal elements come first.
- To find how many elements of Y go before X's current element x, use gallop_left. It counts elements < x, so Y's equal elements stay behind x.
The threshold also adapts. When galloping pays off, Timsort lowers min_gallop so it enters galloping mode sooner next time. When galloping does not pay off, it raises the threshold. On random data galloping rarely starts, so it adds very little cost.
from bisect import bisect_right
def gallop_right(x, a, lo, hi):
"""Return the index after the last element <= x in sorted a[lo:hi]."""
n = hi - lo
last, ofs = 0, 1
while ofs < n and not (x < a[lo + ofs]):
last = ofs
ofs = ofs * 2 + 1 # probe 1, 3, 7, 15, ...
ofs = min(ofs, n)
return bisect_right(a, x, lo + last, lo + ofs)
print(gallop_right(5, [1, 2, 3, 5, 5, 8, 9], 0, 7)) # 5A Working Simplified Timsort
The code below implements runs, minrun, binary insertion sort, the fixed merge policy and a stable merge that buffers the left run. It leaves out galloping and the trimming step to keep it short, but it sorts correctly and stably. Like CPython, it uses only the < operator.
from bisect import bisect_right
def compute_minrun(n):
r = 0
while n >= 64:
r |= n & 1
n >>= 1
return n + r
def count_run(a, lo, hi):
"""Return the end of the run starting at lo; reverse it if strictly descending."""
i = lo + 1
if i == hi:
return hi
if a[i] < a[lo]:
while i + 1 < hi and a[i + 1] < a[i]:
i += 1
a[lo:i + 1] = reversed(a[lo:i + 1])
else:
while i + 1 < hi and not (a[i + 1] < a[i]):
i += 1
return i + 1
def binary_insertion_sort(a, lo, hi, start):
for i in range(start, hi):
x = a[i]
pos = bisect_right(a, x, lo, i) # after equal elements: stable
a[pos + 1:i + 1] = a[pos:i]
a[pos] = x
def merge(a, lo, mid, hi):
left = a[lo:mid]
i, j, k = 0, mid, lo
while i < len(left) and j < hi:
if a[j] < left[i]: # strict: ties go to the left run
a[k] = a[j]; j += 1
else:
a[k] = left[i]; i += 1
k += 1
a[k:k + len(left) - i] = left[i:]
def merge_at(a, runs, i):
start_a, len_a = runs[i]
start_b, len_b = runs[i + 1]
merge(a, start_a, start_b, start_b + len_b)
runs[i] = (start_a, len_a + len_b)
del runs[i + 1]
def merge_collapse(a, runs):
while len(runs) > 1:
n = len(runs) - 2
if (n > 0 and runs[n - 1][1] <= runs[n][1] + runs[n + 1][1]) or \
(n > 1 and runs[n - 2][1] <= runs[n - 1][1] + runs[n][1]):
if runs[n - 1][1] < runs[n + 1][1]:
n -= 1
merge_at(a, runs, n)
elif runs[n][1] <= runs[n + 1][1]:
merge_at(a, runs, n)
else:
break
def timsort(a):
n = len(a)
minrun = compute_minrun(n)
runs, lo = [], 0
while lo < n:
end = count_run(a, lo, n)
if end - lo < minrun:
forced = min(lo + minrun, n)
binary_insertion_sort(a, lo, forced, end)
end = forced
runs.append((lo, end - lo))
merge_collapse(a, runs)
lo = end
while len(runs) > 1:
merge_at(a, runs, len(runs) - 2)
return a
if __name__ == "__main__":
import random
class Rec:
def __init__(self, k, i):
self.k, self.i = k, i
def __lt__(self, other):
return self.k < other.k
data = [Rec(random.randrange(10), i) for i in range(5000)]
expected = [(r.k, r.i) for r in sorted(data, key=lambda r: r.k)]
got = [(r.k, r.i) for r in timsort(list(data))]
print(got == expected) # TrueThe test compares the result with Python's built-in stable sort on records that have many duplicate keys. If any equal records swapped places, the index lists would differ.
Costs and Edge Cases
| Input | Comparisons | Extra memory |
|---|---|---|
| Already sorted | n − 1 | O(1) |
| Strictly descending | n − 1, plus an O(n) reversal | O(1) |
| Random | O(n log n) | up to n/2 elements |
| Sorted with a few appended items | close to O(n) | small |
| Many interleaved sorted blocks | close to O(n log r) for r runs | up to n/2 elements |
Some behaviours to know:
- Non-strict descending input such as
[3, 3, 2, 2, 1, 1]breaks into many short runs, because a descending run has to be strict. Timsort still sorts it correctly but gets less benefit from the existing order. - Comparison cost dominates. Timsort was tuned for Python, where each comparison calls a method and is slow. It saves comparisons at the cost of moving more data. That is a good trade for objects and a poorer one for machine integers, which is why Java uses dual-pivot quicksort for primitive arrays.
- Inconsistent comparators can make Java's Timsort throw
IllegalArgumentException: Comparison method violates its general contract!Galloping and the run checks rely on the ordering being consistent. - Mutation during sorting. CPython empties the list while it sorts and raises
ValueErrorif a key function or comparison changes the list.
Exercise
Why does Timsort reverse only strictly descending runs instead of every non-ascending run?
Show answer
Reversing a run that contains equal elements would swap their relative order and break stability. A strictly descending run has no equal elements, so reversing it is safe.
Exercise
During merge_lo, Timsort gallops through the left run X to find where the right run's current element y belongs. Should it count elements of X that are < y or elements that are <= y? Why?
Show answer
It should count elements <= y, which is gallop_right. Elements of X equal to y came earlier in the input, so they must be placed before y to keep the sort stable.
Exercise
For n = 1000, what minrun does compute_minrun return, and about how many runs will random input produce?
Show answer
1000 in binary is 1111101000. Shifting right until the value is below 64 gives 62 (111110), and one of the shifted-out bits was 1, so minrun = 63. 1000 / 63 is about 15.9, so random input produces about 16 runs, close to the power of two 16.