Sub topic 11
Practical Optimizations and Hybrid Sorts like Timsort
This chapter assumes you have already worked through the earlier chapters. You should be comfortable with the top-down and bottom-up merge sort implementations, the T(n) = 2T(n/2) + O(n) analysis, and why the merge uses <= to stay stable. You should also be able to read Python that sorts a list in place using index ranges.
The textbook merge sort is optimal in the asymptotic sense, but production sorts rarely ship it unchanged. Its constant factors are large: it makes a function call for every tiny subarray, copies every element at every level, and ignores order that already exists in the input. This chapter covers the standard fixes one by one, then shows how Timsort combines them into a hybrid sort that runs in O(n) on already-sorted data and still guarantees O(n log n) in the worst case.
Where the Plain Version Wastes Time
Profile a naive merge sort on a million integers and three costs dominate:
- Recursion overhead near the leaves. About half of all calls are on subarrays of size 1, and about three quarters are on size 2 or less. Each call pays for a stack frame, slicing, and list allocation while doing almost no comparisons.
- Unnecessary merges. If the left half's last element is already
<=the right half's first element, the merge only copies data around. - Allocation and copying. The slicing version from earlier chapters allocates new lists at every level. Most of that memory traffic can be avoided.
None of these change the Big-O bound. They change the constant, and on sorted or nearly sorted input they can also change the actual growth rate.
Optimization 1: An Insertion-Sort Cutoff
Insertion sort costs O(k²) on k elements, but it has a tiny inner loop, no recursion, and no extra memory. For small k (typically 8 to 64, depending on language and hardware) it beats merge sort. The fix is to stop recursing once a subarray is small and sort it with insertion sort instead.
The cutoff keeps the overall bound. With cutoff c, there are about n/c leaf subarrays, each costing O(c²), for O(nc) total. The recursion tree above the leaves has log₂(n/c) levels of O(n) work. Since c is a constant, the total is still O(n log n).
Optimization 2: Skip Merges That Are Already in Order
After both halves are sorted, one comparison tells you whether a merge is needed at all: if a[mid - 1] <= a[mid], the whole range is already sorted. This check costs O(1) per call. On input that is already sorted, every merge gets skipped and the running time drops to O(n). The recurrence becomes T(n) = 2T(n/2) + O(1).
Optimization 3: One Auxiliary Buffer, Allocated Once
Allocate a single auxiliary array of size n at the start and pass it down through the recursion, instead of slicing new lists. The merge copies the range into the buffer and writes the result back into the original array. The bottom-up chapter showed a further step, swapping the roles of source and destination at each level so you skip the copy-back. Here the simpler copy-then-merge form keeps the code readable.
Here are all three optimizations together:
import random
CUTOFF = 16
def insertion_sort(a, lo, hi):
"""Sort a[lo:hi] in place; stable because it shifts only on strict >."""
for i in range(lo + 1, hi):
x = a[i]
j = i - 1
while j >= lo and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
def merge(a, aux, lo, mid, hi):
aux[lo:hi] = a[lo:hi]
i, j = lo, mid
for k in range(lo, hi):
if i < mid and (j >= hi or aux[i] <= aux[j]):
a[k] = aux[i]
i += 1
else:
a[k] = aux[j]
j += 1
def _sort(a, aux, lo, hi):
if hi - lo <= CUTOFF:
insertion_sort(a, lo, hi)
return
mid = (lo + hi) // 2
_sort(a, aux, lo, mid)
_sort(a, aux, mid, hi)
if a[mid - 1] <= a[mid]: # halves already in order: skip the merge
return
merge(a, aux, lo, mid, hi)
def merge_sort(items):
a = list(items)
aux = [None] * len(a) # allocated once, reused by every merge
_sort(a, aux, 0, len(a))
return a
data = [random.randint(0, 1000) for _ in range(10_000)]
assert merge_sort(data) == sorted(data)
assert merge_sort(range(5000)) == list(range(5000))
print(merge_sort([38, 27, 43, 3, 9, 82, 10])) # [3, 9, 10, 27, 38, 43, 82]The table summarizes what each change buys:
| Optimization | Cost added | Effect on random input | Effect on sorted input |
|---|---|---|---|
| Insertion-sort cutoff | None | Constant-factor speedup, often 10–30% | Insertion sort on sorted leaves is linear |
| Skip ordered merges | One comparison per call | Negligible | Running time drops to O(n) |
| Single reused buffer | None | Fewer allocations, better cache use | Same |
| Alternating buffers (bottom-up) | Slightly trickier code | Removes the copy-back | Same |
From Tweaks to a Hybrid: Timsort
The optimizations above still split the array at fixed midpoints, so they ignore structure that doesn't line up with those midpoints. Real data often contains runs, stretches that are already ascending or descending: appended log entries, a sorted list with a few new items at the end, or two sorted lists concatenated. Tim Peters designed Timsort for Python in 2002 to find and use those runs. Java uses it for sorting object arrays, and Android, V8 (JavaScript), and Swift ship variants of it.
Run Detection
Timsort scans from the current position for the longest ascending run (a[i] <= a[i+1]) or strictly descending run (a[i] > a[i+1]), and reverses descending runs in place. The descending test must be strict. Reversing a run that contains equal elements would swap their order and break stability.
minrun
Runs that are too short would make the merges unbalanced and expensive. Timsort picks a value minrun between 32 and 64 so that n / minrun is a power of two or slightly below one, which keeps the later merges balanced. Any natural run shorter than minrun is extended to that length with insertion sort. CPython uses binary insertion sort here to cut down on comparisons. For n < 64, minrun is simply n, so the whole array is insertion-sorted.
The Merge Stack and Its Invariants
Each run is pushed onto a stack. If the top three run lengths are A, B, C (C on top), Timsort merges until both of these hold:
A > B + CB > C
These rules make the run lengths grow at least as fast as Fibonacci numbers going down the stack. That keeps the stack depth at O(log n) and means each merge combines runs of similar size, which is what gives the O(n log n) bound.
Merging and Galloping
When Timsort merges two adjacent runs, it copies only the smaller run into temporary memory. That roughly halves the extra space in practice, though the worst case is still n/2. During the merge it counts how many times in a row one side wins. After MIN_GALLOP wins in a row (7 initially, then adjusted as the sort goes), it switches to galloping: an exponential search (probe positions 1, 3, 7, 15, …, then binary search) for where the next element from the other run belongs, followed by a block copy. On data where runs barely interleave, galloping turns a merge that would cost a linear number of comparisons into one that costs a logarithmic number.
A Simplified Timsort
The version below includes run detection, minrun, the corrected stack invariants, and a merge that copies only the left run into temporary memory. It leaves out galloping and binary insertion sort, so it is correct and stable but slower than the real thing.
import random
def insertion_sort(a, lo, hi):
for i in range(lo + 1, hi):
x = a[i]
j = i - 1
while j >= lo and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
def compute_minrun(n):
r = 0
while n >= 64:
r |= n & 1
n >>= 1
return n + r
def count_run(a, lo, n):
"""Return the length of the run starting at lo, reversing it if descending."""
hi = lo + 1
if hi == n:
return 1
if a[hi] < a[lo]: # strictly descending
while hi + 1 < n and a[hi + 1] < a[hi]:
hi += 1
a[lo:hi + 1] = a[lo:hi + 1][::-1]
else: # non-descending
while hi + 1 < n and a[hi + 1] >= a[hi]:
hi += 1
return hi - lo + 1
def merge_runs(a, lo, mid, hi):
left = a[lo:mid] # copy only the left run
i, j, k = 0, mid, lo
while i < len(left) and j < hi:
if left[i] <= a[j]:
a[k] = left[i]
i += 1
else:
a[k] = a[j]
j += 1
k += 1
a[k:k + len(left) - i] = left[i:] # leftover right items are already in place
def merge_at(a, runs, i):
start1, len1 = runs[i]
start2, len2 = runs[i + 1]
merge_runs(a, start1, start2, start2 + len2)
runs[i] = (start1, len1 + len2)
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 mini_timsort(items):
a = list(items)
n = len(a)
if n < 2:
return a
minrun = compute_minrun(n)
runs = [] # stack of (start, length)
lo = 0
while lo < n:
length = count_run(a, lo, n)
if length < minrun:
length = min(minrun, n - lo)
insertion_sort(a, lo, lo + length)
runs.append((lo, length))
lo += length
merge_collapse(a, runs)
while len(runs) > 1:
merge_at(a, runs, len(runs) - 2)
return a
for size in [0, 1, 5, 63, 64, 1000, 20_000]:
data = [random.randint(0, 50) for _ in range(size)]
assert mini_timsort(data) == sorted(data)
assert mini_timsort(list(range(10_000, 0, -1))) == list(range(1, 10_001))
print(mini_timsort([5, 2, 9, 1, 5, 6])) # [1, 2, 5, 5, 6, 9]On a fully ascending or fully descending input, count_run finds one run covering the whole array, nothing gets merged, and the sort finishes in O(n).
Choosing a Cutoff and Common Mistakes
- Tune the cutoff by measuring. In Python, interpreter overhead per call is high, so cutoffs near 32–64 often win. In C or Java, 7–16 is typical. Benchmark on your own data.
- Run the ordered check after recursion, not before. You can only compare
a[mid - 1]anda[mid]meaningfully once both halves are sorted. - Keep every step stable. Strict
>in insertion sort,<=in the merge, and reversing only strictly descending runs all matter. - Galloping needs adaptive thresholds. On random data, galloping wastes comparisons. Timsort raises
min_gallopwhen galloping fails and lowers it when it pays off.
Exercise
With a cutoff of c = 16, roughly how many insertion-sort calls does the optimized top-down merge sort make on n = 1,048,576 elements, and why does the total stay O(n log n)?
Show answer
The recursion halves until subarrays have 16 or fewer elements: 2^20 / 2^4 = 2^16 = 65,536 leaf calls of 16 elements each. Insertion sort costs O(c²) per leaf, so the leaves cost O((n/c)·c²) = O(nc), which is O(n) for a constant c. The log₂(n/c) = 16 levels above the leaves do O(n) merge work each. The total is O(n log n).
Exercise
Why does Timsort reverse only strictly descending runs, and what goes wrong if count_run treats [3, 2, 2, 1] as one descending run?
Show answer
Reversing a run turns the first equal element into the last one. With [3, 2a, 2b, 1], reversing gives [1, 2b, 2a, 3], so the two 2s swap their original order and the sort is no longer stable. With the strict test, the run stops at [3, 2a], gets reversed to [2a, 3], and 2b is handled by a later run or by insertion sort, which keeps 2a ahead of 2b.
Exercise
On an already-sorted array of n elements, what is the running time of (a) the plain merge sort from earlier chapters, (b) the optimized mergesort in this chapter, and (c) minitimsort?
Show answer
(a) Θ(n log n), because it always merges at every level. (b) O(n): insertion sort is linear on sorted leaves and every merge above the leaves is skipped after one comparison, so T(n) = 2T(n/2) + O(1). (c) O(n): count_run finds one run of length n in n − 1 comparisons and no merges happen.