Why it matters

Quicksort is the default sort in many standard libraries (with tweaks). Understanding its behavior explains why sometimes-fast sorts become dramatically slow, and how to design pivot selection to keep them fast.

Advertisement

The architecture

Partition step: choose a pivot; rearrange so elements less than pivot are left, greater are right; pivot ends up between them. O(n) work.

Recursion: sort left partition, then right partition. Each partition has smaller n. Base case is 0 or 1 element.

Quicksort structurePick pivotmedian-of-threePartitionless | pivot | greaterRecurseon each sideO(n log n) average when partitions are balanced; O(n²) if pivot always extreme
Divide-and-conquer with pivot.
Advertisement

How it works end to end

Pivot choice matters. Naive first-element pivot gives O(n²) on already-sorted data. Median-of-three (median of first, middle, last) is much better. Random pivot gives expected O(n log n).

Lomuto partition and Hoare partition are two schemes. Hoare has fewer swaps; Lomuto is easier to code correctly.

Tail call optimization: recurse on smaller partition first, iterate on larger. Bounds stack depth to O(log n).