Quicksort
Algorithms · Advanced Placement
Quicksort: the big picture
Quicksort sorts in place by partitioning: choose a pivot, rearrange the array so that elements no greater than the pivot precede it and elements no smaller follow it, and then sort the two parts recursively. The partition procedure runs in linear time with a single pass and a small constant, which together with excellent cache locality is why quicksort is usually the fastest comparison sort in practice despite its worst case. The running time depends entirely on how evenly the partitions split the array: a balanced split at every level gives the linearithmic recurrence, while a maximally unbalanced split, which occurs for sorted input with a naive pivot choice, gives the quadratic recurrence. Crucially, even a consistently lopsided split with a fixed proportion still gives linearithmic time, because the recursion depth remains logarithmic; only splits that remove a constant number of elements are catastrophic. Randomizing the pivot choice makes the expected time linearithmic for every input, with the probability of substantially worse behaviour falling exponentially. Practical implementations add refinements: median-of-three pivot selection, switching to insertion sort for small subarrays, three-way partitioning for repeated keys, and bounding the recursion depth with a fallback to heapsort.
Partitioning, Pivot Choice & Expected Time
Quicksort's whole character comes from the partition step: one linear pass with a tiny constant and excellent cache locality, which is why it usually beats algorithms with the same asymptotic bound. Its running time depends on how evenly the pivot splits the array, and the surprise is how forgiving that is — even a consistent ninety-ten split still gives n log n, because the depth stays logarithmic. Only splits that peel off a constant number of elements are catastrophic, which is exactly what a naive pivot does on sorted input.
{{illustration:algos-l06-f1}}
{{illustration:algos-l06-f2}}
Key relations
- Quicksort's recurrences. T(n) = 2T(n/2) + Θ(n) = Θ(nlog n) ; T(n) = T(n−1) + Θ(n) = Θ(n²)
Introsort, Small-Case Cutoffs & Adaptive Sorting
Production sorts are hybrids, because each pure algorithm has a weakness. Introsort runs quicksort but counts its recursion depth and switches to heapsort if it goes too deep, which gives quicksort's speed with heapsort's guarantee. Below a few dozen elements insertion sort wins outright on constants, so libraries cut over. Timsort goes further and exploits existing runs in the data, which makes it linear on nearly-sorted input — a common case that the asymptotic analysis of random input completely ignores.
{{illustration:algos-l06-f3}}
{{illustration:algos-l06-f4}}
Key relations
- Hybrid sorting bounds. Tᵢₙₜᵣₒₛₒᵣₜ(n) = O(nlog n) worst case ; T_Timsort(n) = Ω(n) on sorted input