Sub topic 13
Where Insertion Sort Survives: Small Runs in Hybrid Sorts
This chapter assumes you know insertion sort and its O(n²) worst case, what inversions are, and how quicksort and merge sort split a problem recursively. Bubble sort and selection sort rarely appear in production code. Insertion sort does appear, inside the sorting routines of major language runtimes.
Why an O(n²) Sort Wins on Small Inputs
Big-O describes growth as n becomes large. It hides constant factors, and for small n those constants decide which algorithm is faster. Insertion sort does very little per step:
- It needs no recursion, no function-call overhead and no extra memory.
- It scans memory in order, which suits CPU caches.
- Its inner loop has one comparison and one shift.
- Its work is proportional to n plus the number of inversions, so a nearly sorted chunk costs close to O(n).
Quicksort and merge sort pay a fixed cost for every recursive call. Near the bottom of the recursion, a call may handle only 5 or 10 elements, and that overhead outweighs the work it saves. The fix is to stop recursing below a cutoff size and finish those small pieces with insertion sort.
A Hybrid Quicksort
The quicksort below partitions until a subarray has cutoff elements or fewer. It then sorts that subarray with insertion sort.
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):
mid = (lo + hi) // 2
a[mid], a[hi] = a[hi], a[mid] # use the middle element as pivot
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return 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 and loop on the larger one to bound stack depth.
if p - lo < hi - p:
hybrid_quicksort(a, lo, p - 1, cutoff)
lo = p + 1
else:
hybrid_quicksort(a, p + 1, hi, cutoff)
hi = p - 1
insertion_sort_range(a, lo, hi)
return a
data = [random.randint(0, 999) for _ in range(1000)]
print(hybrid_quicksort(list(data)) == sorted(data)) # TrueWhere Real Libraries Use It
| Library | Main algorithm | Role of insertion sort |
|---|---|---|
| C++ `std::sort` (libstdc++) | Introsort: quicksort, with heapsort as a fallback | Final insertion sort pass over partitions of 16 or fewer elements |
| Java `Arrays.sort` for primitives | Dual-pivot quicksort | Sorts subarrays below a threshold of a few dozen elements |
| Python `list.sort`, Java `Arrays.sort` for objects | Timsort, a merge sort over natural runs | Binary insertion sort extends short runs up to a minimum run length, usually 32 to 64 |
Timsort's case is a good example. Timsort first finds runs, which are stretches of input that are already in order. Any run shorter than the minimum length is extended with binary insertion sort. Binary insertion sort fits here for three reasons:
- In Python, a comparison calls a user-level
__lt__, so comparisons are expensive. Binary search cuts them to O(log i) per element. - Moving elements is a fast block memory copy.
- Inserting with
bisect_rightkeeps the sort stable, and Timsort promises stability.
Exercise
Why does setting the cutoff to 1000 in hybrid_quicksort make sorting a random list of 1,000,000 elements slower?
Show answer
Quicksort then stops partitioning once a subarray has 1000 or fewer elements and sorts each one with insertion sort. On random data a 1000-element block has about 1000²/4 = 250,000 inversions, and each inversion costs one shift. That is far more work than the roughly 1000·log₂1000 ≈ 10,000 steps that further partitioning would take, so the quadratic term dominates the run time.
Exercise
Timsort extends short runs with binary insertion sort rather than plain insertion sort. Which cost does this lower, which cost stays the same, and why does that trade suit Python?
Show answer
Binary search lowers the comparisons per insertion from O(i) to O(log i). The number of element moves stays the same, O(n²) in the worst case. In Python, comparisons call possibly user-defined methods and are expensive, while moves are cheap pointer copies done in bulk. Saving comparisons is therefore worth it.