Quicksort: Analysis
Worst Case:
The worst case occurs when the pivot is always the minimum or maximum element of the subarray, producing a split of and elements. This happens, infamously, when the input is already sorted (or reverse-sorted) with a naive first/last-element pivot choice.
Recurrence:
Using the substitution method:
Even a constant-sized split-off (e.g. consistently producing a subarray of size and for constant ) still yields , because the recurrence becomes .
Best Case:
If the pivot always splits the array exactly in half:
By the Master Theorem (Case 2, ):
Ratio Splits Also Give
A split of to still produces . The recursion tree has depth on the longest path and on the shortest, with at most work per level. In both cases:
An ratio split (any constant fraction on both sides, no matter how unbalanced) guarantees . Only constant-sized splits degrade to .
Average Case:
Assuming random pivot selection (all permutations equally likely), the expected number of comparisons is approximately .
Intuition: any two elements and (with in sorted order) are compared if and only if one of them is chosen as a pivot before any element between them in sorted order. The probability they are compared is . Summing over all pairs:
Thus the expected running time is .
Comparison with MergeSort
| Property | Quicksort | MergeSort |
|---|---|---|
| Worst case | ||
| Average case | ||
| Extra space | (stack) | (merge arrays) |
| Stable | No | Yes |
| Cache behaviour | Excellent (in-place, sequential access) | Good but external merge requires extra memory |
Despite the worst case, Quicksort is often faster than MergeSort in practice because of low constant factors and cache-friendly memory access patterns. The worst case can be mitigated by random pivot selection or median-of-three.
Summary
| Case | Running Time | Condition |
|---|---|---|
| Best | Pivot always splits evenly | |
| Average | Random pivot; expected comparisons | |
| Worst | Pivot always min or max | |
| Ratio split | Any constant fraction split | |
| Constant split | Splitting off constant-size chunk | |
| Key insight | Unbalanced but proportional splits are fine; constant-remainder splits are disastrous |