Sub topic 13
Where Insertion Sort Survives: Small Runs in Hybrid Sorts
Earlier chapters showed that insertion sort runs in O(n²) time in the worst case. You might expect production libraries to drop it in favor of O(n log n) algorithms. They don't. The sort routines in CPython, Java, C++ standard libraries, and Go all call insertion sort, or its binary variant, on small pieces of the input.
This chapter assumes you can read recursive Python, know how quicksort partitions an array and how merge sort merges, and remember the results on inversions and binary insertion sort from earlier chapters.
Why Asymptotics Mislead at Small n
Big-O drops constant factors, and at small n those constants decide which algorithm is faster. A rough cost model makes this concrete:
- Insertion sort on random input does about n²/4 comparisons and n²/4 shifts. Its inner loop is a single compare and a single move, with no function calls and no extra memory.
- Quicksort or merge sort does about c · n log₂ n operations. Each recursive call adds overhead: stack frames, index arithmetic, pivot selection, and for merge sort, copying into a buffer.
If one quicksort "step" costs several times as much as one insertion sort step, then n²/4 stays below c · n log₂ n until n reaches somewhere in the low dozens. Below that crossover point, insertion sort wins on wall-clock time.
Insertion sort also has properties that matter on real hardware:
| Property | Why it helps on small subarrays |
|---|---|
| Sequential memory access | The inner loop walks left through adjacent cells, which suits CPU caches and prefetchers. |
| No recursion | Removes call overhead, which dominates when a subarray has only a few elements. |
| In place | Needs no buffer allocation or copying. |
| Adaptive | Runs in O(n + I), where I is the number of inversions, so partially ordered pieces sort quickly. |
| Stable | Can be used inside stable sorts such as Timsort without breaking their guarantee. |
The hybrid pattern follows from these properties. A divide-and-conquer algorithm handles the large-scale structure, and once a piece falls below a size threshold called the cutoff, insertion sort finishes it.
Pattern 1: Quicksort with an Insertion Sort Cutoff
The most common hybrid stops recursing when a subarray has cutoff or fewer elements and sorts it with insertion sort instead.
import random
def insertion_sort_range(a, lo, hi):
"""Sort a[lo..hi] (inclusive) in place."""
for i in range(lo + 1, hi + 1):
key = a[i]
j = i - 1
while j >= lo and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
def partition(a, lo, hi):
"""Hoare partition. Returns p with a[lo..p] <= pivot <= a[p+1..hi]."""
pivot = a[(lo + hi) // 2]
i, j = lo - 1, hi + 1
while True:
i += 1
while a[i] < pivot:
i += 1
j -= 1
while a[j] > pivot:
j -= 1
if i >= j:
return j
a[i], a[j] = a[j], a[i]
def hybrid_quicksort(a, lo=0, hi=None, cutoff=16):
if hi is None:
hi = len(a) - 1
while hi - lo + 1 > cutoff:
p = partition(a, lo, hi)
# Recurse on the smaller side so stack depth stays O(log n).
if p - lo < hi - p:
hybrid_quicksort(a, lo, p, cutoff)
lo = p + 1
else:
hybrid_quicksort(a, p + 1, hi, cutoff)
hi = p
insertion_sort_range(a, lo, hi)
return a
random.seed(0)
data = [random.randint(0, 999) for _ in range(10_000)]
assert hybrid_quicksort(data[:]) == sorted(data)
assert hybrid_quicksort([]) == []
assert hybrid_quicksort([3, 3, 3, 1]) == [1, 3, 3, 3]
print("ok")The cutoff removes the bottom few levels of the recursion tree. In a balanced quicksort, those levels hold most of the calls: about half of all calls work on subarrays of size 1 or 2. Replacing them with tight insertion sort loops cuts total overhead, while each leaf still costs only O(cutoff²), which is a constant.
Pattern 2: Leave Small Pieces Unsorted, Then One Final Pass
The GNU C++ library (libstdc++) uses a different version in std::sort. Quicksort stops at the cutoff but leaves the small pieces unsorted. After partitioning finishes, a single insertion sort runs over the whole array.
def quicksort_coarse(a, lo, hi, cutoff):
"""Partition until every piece has at most `cutoff` elements, then stop."""
while hi - lo + 1 > cutoff:
p = partition(a, lo, hi)
if p - lo < hi - p:
quicksort_coarse(a, lo, p, cutoff)
lo = p + 1
else:
quicksort_coarse(a, p + 1, hi, cutoff)
hi = p
def deferred_hybrid(a, cutoff=16):
quicksort_coarse(a, 0, len(a) - 1, cutoff)
insertion_sort_range(a, 0, len(a) - 1)
return a
random.seed(1)
data = [random.randint(0, 999) for _ in range(10_000)]
assert deferred_hybrid(data[:]) == sorted(data)
print("ok")The inversions chapter explains why one full pass is cheap. After the coarse phase, the array is a sequence of blocks, each with at most cutoff elements, and every element of a block is ≤ every element of later blocks. Inversions can only occur inside a block. A block of size k has at most k(k − 1)/2 inversions, so the whole array has at most n(cutoff − 1)/2. Insertion sort runs in O(n + I), so the final pass costs O(n · cutoff), which is linear for a fixed cutoff.
This version also needs fewer insertion sort calls and fewer boundary checks. libstdc++ goes one step further. Once the first block is sorted, it knows a smaller element sits to the left of every later element, so it uses an "unguarded" inner loop that skips the j >= lo test.
Pattern 3: Timsort and Binary Insertion Sort on Runs
Timsort is the stable sort behind Python's list.sort and sorted. Java also uses it for Arrays.sort on object arrays. Timsort is a merge sort that looks for runs, which are stretches of the input that are already ascending or strictly descending. It reverses descending runs in place. Reversal is safe only for strictly descending runs, because reversing equal elements would break stability.
Real data often contains many short runs, and merging tiny runs is wasteful. So Timsort sets a minimum run length, minrun. If a natural run is shorter than minrun, Timsort extends it to minrun elements by inserting the following elements into it with binary insertion sort. Arrays smaller than 64 elements are sorted entirely by binary insertion sort, with no merging.
CPython chooses minrun so that n / minrun is equal to, or slightly less than, a power of two. That choice keeps the later merges balanced:
def min_run_length(n):
"""CPython's minrun rule: take the top 6 bits of n, add 1 if any lower bit is set."""
r = 0
while n >= 64:
r |= n & 1
n >>= 1
return n + r
print([min_run_length(n) for n in (63, 64, 65, 100, 1000, 2**20)])
# [63, 32, 33, 50, 63, 32]For n ≥ 64, minrun falls between 32 and 64. Java's TimSort uses the same rule with a threshold of 32, which gives runs of 16 to 32 elements.
Timsort uses the binary variant because of its cost model. In CPython, each comparison calls the objects' __lt__ method, which can be slow for strings, tuples, or user-defined classes. Moving elements is a memmove of pointers, which is very fast. Binary insertion sort cuts comparisons from O(k²) to O(k log k) for a run of length k. It still makes O(k²) moves, but at k ≤ 64 those moves are cheap. This matches the trade-off from the binary insertion sort chapter, and Timsort uses the variant in exactly the setting where that trade-off pays off.
Real Libraries at a Glance
Implementations change between versions. The table describes well-known versions and should not be read as a permanent guarantee.
| Library and routine | Outer algorithm | Small-input sort | Threshold |
|---|---|---|---|
| CPython `list.sort` | Timsort (Powersort merge policy since 3.11) | Binary insertion sort to extend runs | minrun 32–64; whole array if n < 64 |
| Java `Arrays.sort(Object[])` | TimSort | Binary insertion sort | runs of 16–32; whole array if n < 32 |
| Java `Arrays.sort(int[])`, JDK 7–13 | Dual-pivot quicksort | Insertion sort | 47 elements |
| libstdc++ `std::sort` | Introsort (quicksort, heapsort fallback) | Final insertion sort pass | 16 elements |
| Go `sort` / `slices`, 1.19+ | Pattern-defeating quicksort | Insertion sort | 12 elements |
Introsort and pdqsort also guard against quicksort's O(n²) worst case by switching to heapsort when recursion gets too deep. Insertion sort handles the small end of the size range, and heapsort handles adversarial inputs at the large end.
Choosing the Cutoff
The best cutoff depends on how expensive a comparison or move is compared with a recursive call. You can measure it:
import random
import timeit
random.seed(2)
base = [random.random() for _ in range(20_000)]
for cutoff in (1, 4, 8, 16, 32, 64, 128):
t = timeit.timeit(lambda: hybrid_quicksort(base[:], cutoff=cutoff), number=5)
print(f"cutoff={cutoff:4d} {t:.3f}s")Typically the curve falls from cutoff 1, flattens somewhere in the range 8 to 32, and rises again as the O(cutoff²) leaf cost takes over. The minimum is broad, so a value anywhere near it works about as well as the exact best.
Failure modes to watch:
- Cutoff too large. Leaf cost grows as cutoff², and the leaves can come to dominate the running time, especially when comparisons are expensive.
- Expensive comparisons. If comparing two keys costs much more than moving them, plain insertion sort's quadratic comparison count hurts. Switch to binary insertion sort, as Timsort does, or lower the cutoff.
- Large records stored by value. Shifting moves entire records. Sort an array of indices or pointers instead, or lower the cutoff.
- Off-by-one bounds.
insertion_sort_rangemust respectlo. A loop that runs down to index 0 inside a subarray is still correct but no longer linear in the subarray size, and in Pattern 1 it can reach into neighboring pieces.
Exercises
Exercise
In the deferred-pass hybrid (Pattern 2) with cutoff 16 and n = 1,000,000, what is an upper bound on the number of shifts the final insertion sort pass performs, and why?
Show answer
Inversions exist only inside blocks of at most 16 elements, so each element is inverted with at most 15 others in its block. The total is at most n · 15 / 2 = 7,500,000 inversions. Insertion sort performs one shift per inversion, so the pass makes at most 7,500,000 shifts. That is O(n · cutoff), linear in n.
Exercise
Why does Timsort extend short runs with binary insertion sort instead of plain insertion sort, and why does it reverse only strictly descending runs?
Show answer
In CPython, comparisons call Python-level methods and are expensive, while moves are cheap pointer memmoves. Binary insertion sort cuts comparisons to O(k log k) per run of length k, and its O(k²) moves stay cheap because k is at most 64. Timsort reverses only strictly descending runs because reversing a run that contains equal elements would swap their relative order, which would make the sort unstable.
Exercise
Modify hybrid_quicksort so that its leaves use binary insertion sort from the standard bisect module, keeping the lo/hi bounds. Is the result stable?
Show answer
Replace the leaf call with a loop over i in range(lo + 1, hi + 1): set key = a[i], find pos = bisect.bisect_right(a, key, lo, i), then run a[pos + 1:i + 1] = a[pos:i] followed by a[pos] = key. The leaves are now stable, but the whole sort is still unstable, because Hoare partitioning swaps elements across long distances and can reorder equal keys before any leaf runs.