Short answer: Introsort runs quicksort until the recursion depth passes about 2 log₂ n, then finishes that slice with heapsort. Short slices drop into insertion sort. The worst case becomes O(n log n), the typical case keeps quicksort’s partition, and the sort stays in place and unstable. This is the usual implementation of C++ std::sort.
What the problem actually asks
Quicksort’s expected cost is excellent and its worst case is quadratic. A caller of a general library sort cannot promise that the pivot sequence will be kind. Capping the depth throws the rare bad slice to an algorithm whose worst case is already n log n. The cap has to sit far enough out that random inputs almost never hit it, and close enough that a quadratic explosion cannot get far.
Small slices have the opposite problem. A partition’s setup costs more than sliding a dozen items. Those slices belong to insertion sort.
What the algorithm guarantees
The depth limit is 2 floor(log₂ n), the constant Musser used. Each quicksort level does linear work, and a slice that exceeds the limit spends O(m log m) in heapsort on a slice of length m. The sum is O(n log n) on every input. Extra memory is the O(log n) recursion stack, which the depth limit makes a hard ceiling. The sort is unstable because both the partition and the heap reorder equal keys.
On random data the heap is almost never entered, so the measured time tracks quicksort. On a sorted array with a naive end pivot, the heap fires and the quadratic pattern stops. That is the input the cap is for.
The working steps
- If the slice length is below the insertion threshold, usually around 16, insertion-sort it and return.
- If the remaining depth allowance is 0, heapsort the slice and return.
- Partition. Lomuto’s partition places the pivot and the two recursive slices exclude it. Hoare’s partition returns a cut and both sides must cover the slice.
- Recurse on the two sides with the depth allowance decreased by one.
- The top-level call starts the allowance at 2 floor(log₂ n).
The O(n log n) guarantee is for a comparison sort that may reorder equal keys. A stable sort does not become introsort by adding a depth counter. The heap is a fallback, and a correct partition is still required on the levels that have not yet fallen back.
Approaches that look simpler and fail
| Approach | Why it fails when the depth cap is treated as optional |
|---|---|
| Quicksort with no depth cap | A bad pivot sequence is still Θ(n²). The cap is the difference between an expectation and a worst-case proof. |
| Heapsort on every slice | The worst case is fine and the typical constant and cache behavior of partitioning are thrown away. The hybrid exists to keep those on the common path. |
| A depth limit of log₂ n with a poor pivot | One-sided splits consume the allowance immediately and every slice becomes a heap. The factor 2 leaves room for ordinary unlucky pivots. |
| Calling the result stable because insertion sort is stable | Insertion sort runs only on tiny slices. The partitions above them have already reordered equal keys. |
A stable library sort is timsort or mergesort. A pure in-place n log n sort with no quicksort path is heapsort, which introsort already calls at the cap.
A working example
This Python fragment switches a quicksort slice to heapsort when the depth exceeds 2·floor(log2 n), and it insertion-sorts a slice shorter than 4. The array comes out 1 2 3 4 5 6.
import math
def insertionsort(a, lo, hi):
for i in range(lo + 1, hi):
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 heapsort(a, lo, hi):
def sift(i, end):
while True:
left, right = lo + 2 * (i - lo) + 1, lo + 2 * (i - lo) + 2
best = i
if left < end and a[left] > a[best]:
best = left
if right < end and a[right] > a[best]:
best = right
if best == i:
return
a[i], a[best] = a[best], a[i]
i = best
n = hi - lo
for i in range(lo + n // 2 - 1, lo - 1, -1):
sift(i, hi)
for end in range(hi - 1, lo, -1):
a[lo], a[end] = a[end], a[lo]
sift(lo, end)
def introsort(a):
limit = 2 * math.floor(math.log2(max(len(a), 2)))
def rec(lo, hi, depth):
if hi - lo < 4:
insertionsort(a, lo, hi)
return
if depth == 0:
heapsort(a, lo, hi)
return
pivot = a[hi - 1]
i = lo
for j in range(lo, hi - 1):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi - 1] = a[hi - 1], a[i]
rec(lo, i, depth - 1)
rec(i + 1, hi, depth - 1)
rec(0, len(a), limit)
a = [3, 6, 1, 5, 2, 4]
introsort(a)
assert a == [1, 2, 3, 4, 5, 6]
print(*a)
Where it is used
C++ std::sort is introsort: quicksort, a depth limit, then heapsort, with insertion sort on tiny slices. That is the unstable in-place sort in production C++. A stable sort is a separate function because introsort does not keep equal elements in order.
When you can drop this algorithm
Drop introsort when equal keys must keep their input order. Use timsort or mergesort. Keep it for the contract C++ std::sort publishes: an unstable in-place comparison sort with an n log n worst case and quicksort’s speed on ordinary input.
Why this stays published
We publish this so a search for introsort returns the depth cap that turns quicksort’s worst case into a heap. Introsort is quicksort with a 2 log n depth cap into heapsort, which makes the worst case n log n while ordinary input still partitions.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
