Chapter 5 of 12All chapters
Chapter 5 of 12
Sorting and its floor
Why O(n log n) is the wall.
The lower bound
Any algorithm that sorts by comparing pairs needs at least O(n log n) comparisons in the worst case. Merge sort and heap sort meet that bound every time.
- Quicksort averages O(n log n) but degrades to O(n squared) when the pivot splits badly.
- Most standard libraries use a hybrid such as Timsort, tuned for partly sorted input.
Beating the bound
Counting sort and radix sort run in linear time because they never compare two values. They need extra assumptions, such as small integer keys, so they are specialist tools.