Sub topic 15
Introsort: Quicksort in Production Libraries
Earlier chapters gave you several separate fixes for quicksort's weak spots. Better pivots lower the chance of bad splits. Recursing on the smaller side first keeps the stack shallow. Insertion sort handles tiny subarrays faster than further partitioning. None of these fixes guarantees O(n log n) time, though. A carefully built input can still defeat median-of-three, and even random pivots only give a bound on the expected time.
Introsort closes that gap. David Musser introduced it in 1997. It runs ordinary quicksort, tracks how deep the recursion has gone, and switches to heapsort on any subarray where quicksort appears to be going badly. The result has quicksort's speed on typical inputs and a guaranteed O(n log n) worst case.
This chapter assumes you already know Lomuto partitioning, median-of-three, the smaller-side-first recursion trick, and the insertion-sort cutoff from earlier chapters. You should also know what a binary heap is. You don't need to have implemented heapsort before.
The core idea: a depth budget
Quicksort's worst case happens when partitions are badly unbalanced. Each level of recursion then strips off only a few elements, so the depth grows toward n and the total work grows toward n². Balanced partitions produce a depth of about log₂ n.
Recursion depth therefore tells you how well quicksort is doing, and checking it is cheap. Introsort gives each call a depth limit, usually 2·⌊log₂ n⌋. Each level of partitioning spends one unit of that budget. When a subarray's budget reaches zero, introsort stops partitioning that subarray and sorts it with heapsort, which runs in O(m log m) time on m elements whatever the input.
Introsort makes the choice separately for each subarray. One unlucky region of the array can fall back to heapsort while the rest finishes with quicksort.
Why the worst case becomes O(n log n)
Split the work into its three phases:
- Quicksort phase. At any one recursion level, the subarrays don't overlap, so partitioning all of them costs O(n) in total. There are at most 2 log₂ n levels, so this phase costs O(n log n).
- Heapsort phase. The subarrays that hit the depth limit don't overlap either. Heapsorting pieces of sizes m₁, m₂, … costs at most Σ mᵢ log mᵢ ≤ n log n.
- Insertion-sort phase. Each small subarray has at most CUTOFF elements, so it costs O(CUTOFF²). With at most n/1 such pieces and a constant cutoff, this phase is O(n · CUTOFF), which is O(n).
Adding the three gives O(n log n) for every input. On typical inputs the heapsort phase never runs, and introsort behaves like a well-tuned quicksort.
Why 2 log₂ n?
With random pivots, the expected recursion depth of quicksort is around 2 ln n ≈ 1.39 log₂ n, and the actual depth rarely goes much past that. A limit of 2 log₂ n leaves enough room that normal inputs almost never trigger the fallback, while still catching quadratic behavior well before it costs much. A limit set too low would hand ordinary inputs to heapsort, which is usually slower because it reads memory in a scattered pattern. A limit set too high would let quadratic behavior run longer before the fallback kicks in.
A complete implementation
The code below combines every technique from the earlier chapters. It runs as shown.
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 sift_down(a, lo, root, size):
# Max-heap stored in a[lo .. lo+size-1]; indices are relative to lo.
while True:
child = 2 * root + 1
if child >= size:
return
if child + 1 < size and a[lo + child] < a[lo + child + 1]:
child += 1
if a[lo + root] < a[lo + child]:
a[lo + root], a[lo + child] = a[lo + child], a[lo + root]
root = child
else:
return
def heapsort(a, lo, hi):
n = hi - lo + 1
for start in range(n // 2 - 1, -1, -1):
sift_down(a, lo, start, n)
for end in range(n - 1, 0, -1):
a[lo], a[lo + end] = a[lo + end], a[lo]
sift_down(a, lo, 0, end)
def median_of_three_to_hi(a, lo, hi):
mid = (lo + hi) // 2
if a[mid] < a[lo]:
a[mid], a[lo] = a[lo], a[mid]
if a[hi] < a[lo]:
a[hi], a[lo] = a[lo], a[hi]
if a[hi] < a[mid]:
a[hi], a[mid] = a[mid], a[hi]
# Now a[lo] <= a[mid] <= a[hi]; move the median to hi for Lomuto.
a[mid], a[hi] = a[hi], a[mid]
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_loop(a, lo, hi, depth_limit):
while hi - lo + 1 > CUTOFF:
if depth_limit == 0:
heapsort(a, lo, hi)
return
depth_limit -= 1
median_of_three_to_hi(a, lo, hi)
p = lomuto_partition(a, lo, hi)
if p - lo < hi - p:
introsort_loop(a, lo, p - 1, depth_limit)
lo = p + 1
else:
introsort_loop(a, p + 1, hi, depth_limit)
hi = p - 1
insertion_sort(a, lo, hi)
def introsort(a):
n = len(a)
if n < 2:
return
depth_limit = 2 * (n.bit_length() - 1) # 2 * floor(log2 n)
introsort_loop(a, 0, n - 1, depth_limit)
if __name__ == "__main__":
tests = {
"random": [random.randint(0, 10**6) for _ in range(50_000)],
"sorted": list(range(50_000)),
"reversed": list(range(50_000, 0, -1)),
"all equal": [7] * 50_000,
"few distinct": [random.randint(0, 3) for _ in range(50_000)],
}
for name, data in tests.items():
expected = sorted(data)
introsort(data)
print(f"{name:>12}: {'ok' if data == expected else 'FAILED'}")Here are the parts worth looking at closely.
- The depth limit decreases inside the loop. When the loop goes on to the larger side, that side is one level deeper than the subarray just partitioned, so it has to receive the reduced budget. If you decremented only before recursive calls, the larger side would keep its full budget, and repeated bad splits could run for O(n) levels.
n.bit_length() - 1computes ⌊log₂ n⌋ exactly with integer arithmetic, which avoids floating-point rounding inmath.log2.- Heapsort works on a slice with offsets.
sift_downtreatsa[lo]as the heap root, so the fallback sorts just the troublesome subarray in place.
Variations you'll find in real libraries
Musser's paper and some library implementations skip insertion sort inside the loop. They leave every small subarray unsorted and run one insertion-sort pass over the whole array at the end. That works because after the loop every element sits within CUTOFF positions of its final place, so the single pass costs O(n · CUTOFF). It saves function-call overhead, but the depth-limited heapsort pieces have to be handled consistently with it.
| Library | Unstable sort algorithm | Worst-case guard |
|---|---|---|
| C++ libstdc++ `std::sort` | Introsort, median-of-three, threshold 16, final insertion pass | Heapsort at depth 2·⌊log₂ n⌋ |
| .NET `Array.Sort` | Introsort, insertion sort for partitions of 16 or fewer elements | Heapsort when the depth limit is reached |
| Go `sort` / `slices` (1.19+) | Pattern-defeating quicksort (pdqsort) | Heapsort fallback after too many bad partitions |
| Rust `sort_unstable` | pdqsort descendants | Heapsort fallback |
| Java `Arrays.sort` (primitives) | Dual-pivot quicksort | Heapsort fallback in recent JDKs |
Pdqsort, by Orson Peters, extends introsort. It counts unbalanced partitions instead of raw depth. It also detects runs that are already sorted, uses three-way-style handling when it sees many equal keys, and shuffles a few elements after a bad split to break up adversarial patterns. It's still quicksort with a heapsort guarantee underneath.
Failure modes and decision criteria
- The fallback triggers too often. This happens when the pivot rule is weak, or when duplicate keys combine with two-way partitioning, as in the all-equal test above. Correctness holds, but you get heapsort's speed instead of quicksort's. Three-way partitioning or a pdqsort-style duplicate check fixes it.
- A bad comparator. If the comparison isn't a strict weak ordering (for example,
<=used in place of<), Hoare-style unguarded scans in C++ can run past the array bounds. Many crashes blamed onstd::sortcome from this. - Very small or nearly sorted inputs. Introsort doesn't detect existing order. For inputs that are mostly sorted, Timsort or pdqsort do much less work.
Pick introsort or pdqsort when you need fast, in-place, unstable sorting of values in memory with a guaranteed worst case. Pick a stable merge-based sort when order of equal keys matters or when the input often has long sorted runs.
Exercise
In the implementation above, suppose you moved depth_limit -= 1 so it happens only in the argument of the recursive call (passing depth_limit - 1), leaving the loop's own depth_limit unchanged. Which inputs would still run in quadratic time, and why?
Show answer
Inputs where the larger side is chosen for the loop at each step, such as the all-equal array with Lomuto partitioning. Every split puts one element on the small side and the rest on the large side. The loop processes the large side with an unchanged budget, so the depth limit never reaches zero along that path, heapsort never runs, and the work grows to about n²/2 comparisons.
Exercise
For n = 1,000,000, what depth limit does introsort use, and roughly how much deeper is that than the expected depth of randomized quicksort?
Show answer
⌊log₂ 1,000,000⌋ = 19, so the limit is 38. The expected depth is about 1.39 × log₂ n ≈ 1.39 × 19.9 ≈ 28, which leaves about 10 levels of slack before the heapsort fallback would trigger.
Exercise
Explain why heapsorting all the subarrays that hit the depth limit costs O(n log n) in total, even when there are many of them.
Show answer
Those subarrays don't overlap, so their sizes m₁, m₂, … add up to at most n. Heapsorting a piece of size mᵢ costs O(mᵢ log mᵢ) ≤ O(mᵢ log n). Summing over all the pieces gives O(log n · Σ mᵢ) = O(n log n).