The Comparison Lower Bound on Sorting
No sorting algorithm that only compares pairs of elements can beat roughly n log n comparisons in the worst case, and the proof is a clean counting argument about how many possible orderings exist.
Merge sort and heap sort both run in time, and a natural interview follow-up is: can a cleverer algorithm do better? For any algorithm that sorts purely by comparing pairs of elements (asking "is ?" and nothing else), the answer is no — comparisons, up to a constant factor, is provably the best possible in the worst case, for any input size .
The proof is a counting argument, not an algorithmic one. Any comparison-based sorting algorithm can be modelled as a decision tree: each internal node is one comparison, each branch is one possible outcome, and each leaf corresponds to one final, fully determined ordering of the input. For distinct elements there are possible orderings, and the algorithm must be able to reach a distinct leaf for every one of them — a tree with fewer than leaves would have two different true orderings mapping to the same leaf, meaning the algorithm couldn't tell them apart. A binary tree with leaves must have depth at least , and by Stirling's approximation , which is . Since the tree's depth is exactly the worst-case number of comparisons the algorithm might need, no comparison-based algorithm can have worst-case comparisons below .
For elements there are possible orderings, requiring comparisons in the worst case at minimum — matching what insertion sort or merge sort actually need on 4 elements, confirming the bound is tight, not just a loose estimate.
Any comparison-based sort must distinguish all possible orderings, forcing a decision tree of depth at least — which is why no comparison sort can ever beat in the worst case, and why non-comparison sorts (radix, counting sort) are the only way around this bound.
Related concepts
Practice in interviews
Further reading
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms (comparison sort lower bound chapter)