Algorithm Deep Dives

Introsort Explained

Introsort is the hybrid algorithm behind C++ std::sort, combining Quick Sort, Heap Sort, and Insertion Sort. Learn how it guarantees O(n log n) worst case.

Aman Jaiman
6 min read
On this page +
  1. In plain English
  2. Why combine three algorithms?
  3. How Introsort works
  4. Complexity and significance
  5. Frequently asked questions

Introsort (introspective sort) is the algorithm behind C++'s std::sort. It is a hybrid that starts with Quick Sort for speed, switches to Heap Sort if recursion gets too deep to avoid the O(n²) trap, and finishes small partitions with Insertion Sort. The result is Quick Sort's average performance with a guaranteed O(n log n) worst case.

Why combine three algorithms? #

Each component covers a weakness of the others. Quick Sort is fast on average but can hit O(n²). Heap Sort is guaranteed O(n log n) but slower in practice. Insertion Sort is fastest of all on tiny arrays. Introsort uses each where it is strongest.

How Introsort works #

It begins partitioning like Quick Sort while tracking recursion depth, capped at roughly 2·log₂(n). If a branch exceeds that depth — a sign Quick Sort is degenerating — it switches that partition to Heap Sort, which cannot exceed O(n log n). Once partitions shrink below a small threshold (about 16 elements), it stops recursing and runs a single Insertion Sort pass over the whole nearly-sorted array.

Complexity and significance #

Introsort is O(n log n) worst case, in-place with O(log n) stack, and not stable. It is significant because it shows how production libraries combine textbook algorithms to get the best of each — much like Tim Sort does for stable sorting.

Found this useful?

Share it with someone who is learning this too.

Questions

Frequently asked questions

What algorithm does C++ std::sort use? +
Most implementations use Introsort — a hybrid of Quick Sort, Heap Sort, and Insertion Sort that guarantees O(n log n) worst case while keeping Quick Sort's average speed.
How does Introsort avoid Quick Sort's worst case? +
It monitors recursion depth and switches to Heap Sort when depth exceeds about 2·log₂(n), capping the worst case at O(n log n).

See it in motion

Watch this algorithm and nine others run step by step, with live pseudocode and comparison counters.

Launch the visualiser
Aman Jaiman
Written by
Aman Jaiman

Software engineer at a stealth-stage startup, and previously a front-end engineer for around a year and a half.

Keep reading

Related guides

Link copied