Sub topic 15
Introsort: Quicksort in Production Libraries
This chapter assumes you already know the Lomuto partition, why quicksort can go quadratic, how recursing on the smaller side bounds stack depth, and why insertion sort is fast on small subarrays. Introsort combines these ideas into one algorithm. It keeps quicksort's speed on typical inputs and guarantees O(n log n) time on every input.
The problem introsort solves
Randomized pivots make quadratic time unlikely, but they do not rule it out. Median-of-three pivots can still be beaten by inputs built to defeat them. A standard library sort has to finish in O(n log n) time on every input, including input from an attacker.
David Musser proposed introsort ("introspective sort") in 1997. While it runs, the algorithm checks its own progress. If the recursion gets deeper than a balanced quicksort would need, it stops partitioning that subarray and sorts it with heapsort. Heapsort is O(n log n) in the worst case and sorts in place, but it is usually slower than quicksort in practice because it accesses memory in a scattered pattern.
The three parts
| Part | When it runs | Why |
|---|---|---|
| Quicksort | By default | Fastest on typical data |
| Heapsort | When the depth budget runs out | Caps the worst case at O(n log n) |
| Insertion sort | When a subarray has 16 or fewer elements | Has low overhead on small ranges |
The depth budget is usually 2·⌊log₂ n⌋. A reasonably balanced quicksort never uses it all up, so heapsort runs only on bad inputs, and only on the subarrays where partitioning went badly.
A working implementation
import math
import random
CUTOFF = 16
def insertion_sort(a, lo, hi):
for i in range(lo + 1, hi + 1):
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 heapsort(a, lo, hi):
n = hi - lo + 1
def sift_down(root, end):
while True:
child = 2 * root + 1
if child >= end:
return
if child + 1 < end and a[lo + child + 1] > a[lo + child]:
child += 1
if a[lo + root] >= a[lo + child]:
return
a[lo + root], a[lo + child] = a[lo + child], a[lo + root]
root = child
for start in range(n // 2 - 1, -1, -1):
sift_down(start, n)
for end in range(n - 1, 0, -1):
a[lo], a[lo + end] = a[lo + end], a[lo]
sift_down(0, end)
def lomuto_partition(a, lo, hi):
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 _introsort(a, lo, hi, depth):
while hi - lo + 1 > CUTOFF:
if depth == 0:
heapsort(a, lo, hi)
return
depth -= 1
p = lomuto_partition(a, lo, hi)
if p - lo < hi - p:
_introsort(a, lo, p - 1, depth)
lo = p + 1
else:
_introsort(a, p + 1, hi, depth)
hi = p - 1
insertion_sort(a, lo, hi)
def introsort(a):
if len(a) > 1:
_introsort(a, 0, len(a) - 1, 2 * int(math.log2(len(a))))
random_data = [random.randint(0, 1000) for _ in range(10000)]
sorted_data = list(range(10000)) # worst case for a last-element pivot
for data in (random_data, sorted_data):
expected = sorted(data)
introsort(data)
assert data == expected
print("both inputs sorted correctly")On the sorted input, each Lomuto partition peels off only one element. The budget of 26 runs out quickly, and heapsort finishes the job in O(n log n) time instead of the roughly 50 million comparisons plain quicksort would make.
What real libraries use
| Library | Algorithm |
|---|---|
| C++ `std::sort` (libstdc++, MSVC) | Introsort with an insertion-sort pass on small ranges |
| .NET `Array.Sort` | Introsort |
| Go `sort.Sort`, Rust `sort_unstable` | Pattern-defeating quicksort (pdqsort), a descendant of introsort |
| Java `Arrays.sort` for primitives | Dual-pivot quicksort |
| Python `list.sort` | Timsort, a stable merge-based sort |
Python and Java's object sorts use merge-based algorithms because they promise stability. Quicksort-family sorts are not stable.
Exercise
Why does introsort use a depth limit of about 2·log₂ n rather than exactly log₂ n?
Show answer
Random or median-of-three pivots rarely split a range exactly in half, so a healthy run normally goes somewhat deeper than log₂ n. A limit of exactly log₂ n would send many ordinary inputs to the slower heapsort. Doubling the limit leaves room for normal imbalance and still caps total work at O(n log n).
Exercise
In the implementation above, what happens if you set CUTOFF to 0?
Show answer
The code still sorts correctly. The while loop partitions every range with more than 0 elements, which is every range quicksort would normally partition, and then insertion_sort runs on empty ranges and does nothing. You lose the constant-factor speedup that insertion sort gives on small ranges, but the O(n log n) guarantee from the heapsort fallback still holds.