Sub topic 11
Practical Optimizations and Hybrid Sorts like Timsort
This chapter assumes you have already worked through top-down merge sort, the linear-time merge, and the O(n log n) recurrence. You should also be comfortable with insertion sort and index-based array code in Python.
Textbook merge sort is always O(n log n), but its constant factors can be improved. Real libraries rarely ship the plain version. They add a few tweaks that keep the same worst case and make typical inputs much faster.
Where the Plain Version Wastes Time
The plain version loses time in three places:
- Tiny subarrays. Recursion goes all the way down to one element. For small subarrays, the cost of each function call and slice is larger than the useful work being done.
- Fresh allocations. Slicing
items[:mid]and building a newresultlist at every level creates a lot of temporary memory. - Already-ordered halves. If the largest element of the left half is no greater than the smallest element of the right half, the two halves are already in order. The merge then rearranges nothing, but it still copies every element.
An Optimized Array Merge Sort
The version below fixes all three problems. It sorts small ranges with insertion sort and allocates one auxiliary buffer up front. It also skips the merge when the halves are already in order.
import random
CUTOFF = 16
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 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]:
return # halves already in order: skip the merge
merge(a, aux, lo, mid, hi)
def merge_sort(items):
a = list(items)
aux = [None] * len(a)
sort(a, aux, 0, len(a))
return a
data = [random.randint(0, 1000) for _ in range(5000)]
assert merge_sort(data) == sorted(data)
print(merge_sort([38, 27, 43, 3, 9, 82, 10])) # [3, 9, 10, 27, 38, 43, 82]How each change helps:
| Optimization | Effect | Keeps stability? |
|---|---|---|
| Insertion-sort cutoff (about 7 to 32 elements) | Removes the bottom levels of recursion. Insertion sort has a small constant factor on short ranges. | Yes, because it shifts only on strict `>` |
| One shared `aux` buffer | Replaces O(n log n) total allocations with a single O(n) buffer | Yes |
| Skip the merge if `a[mid-1] <= a[mid]` | Already-sorted input runs in O(n) time | Yes |
Timsort: Merge Sort That Exploits Existing Order
Timsort is the hybrid used by Python's sorted and list.sort, and by Java's Arrays.sort for object arrays. It takes the ideas above further.
- Find natural runs. It scans left to right for stretches that are already ascending, or strictly descending. A descending run is reversed in place. Reversing only strictly descending runs keeps the sort stable.
- Enforce a minimum run length. Runs shorter than
minrun(usually 32 to 64) are extended with binary insertion sort. - Merge runs from a stack. New runs are pushed onto a stack, and invariants on the run lengths decide when to merge. This keeps merges balanced, so the worst case stays O(n log n). Python 3.11 replaced the original rules with the "powersort" merge policy.
- Gallop. When one run keeps winning comparisons during a merge, Timsort switches to exponential search. It then copies whole blocks from that run instead of comparing elements one at a time.
Because of these steps, Timsort sorts an already-sorted or reverse-sorted array in O(n) time, and it is fast on partly ordered data, which is common in practice. Its worst case is still O(n log n) with O(n) extra space.
Exercise
Suppose you call the optimized merge_sort above on a list that is already sorted, with n much larger than CUTOFF. How many element comparisons do the skip checks perform across the whole recursion, and what is the overall running time?
Show answer
Every call above the cutoff makes exactly one skip check, a[mid-1] <= a[mid], and it always succeeds, so no merge ever runs. The recursion tree has about n/CUTOFF leaves and about the same number of internal nodes, so there are roughly n/CUTOFF skip comparisons. Each leaf runs insertion sort on an already-sorted range, which costs one comparison per element. The total running time is therefore O(n).
Exercise
Why does Timsort reverse only strictly descending runs instead of every non-increasing run?
Show answer
A non-increasing run can contain equal elements, such as 5, 3, 3, 1. Reversing it would flip the relative order of the two 3s and break stability. Requiring a strictly descending run guarantees that no equal elements are inside it, so reversing is safe.