Which pivot rules protect quick-sort from its worst case on input that is already sorted, and which rule should be avoided?
Avoid the first or the last element: on sorted or reverse-sorted input it is always the minimum or the maximum. Safer are a random element, the middle element, or the median of three (the median of the first, middle and last element).
| Rule | on sorted input | weak spot |
|---|---|---|
| first or last element | $O(n^2)$ | sorted and reverse-sorted input, both common |
| middle element | $O(n \log n)$ | specially constructed inputs still hit the worst case |
| median of three | $O(n \log n)$ | constructed inputs exist as well |
| random element | $O(n \log n)$ expected | no bad input, only bad luck |
The ideal pivot is the median: every split would be an exact halving, and the tree would be as balanced as merge-sort's. Finding the exact median of unsorted data is possible in linear time with a selection algorithm, but its constant factor costs more than it saves, so implementations estimate the median from a small sample. That makes the worst case unlikely, not impossible.
The middle element costs nothing extra and turns sorted input into the best case, since the middle of a sorted range is its median. The median of three is the smallest useful sample: it avoids the extremes and usually gives a better split, at the price of two extra comparisons per call. Library sorts add a safety net on top: introsort, for example, watches the recursion depth and switches to heap-sort once it exceeds about $2 \log_2 n$, which caps the worst case at $O(n \log n)$.
Go deeper:
Introsort — quick-sort with a depth limit and a heap-sort fallback, as used in C++ standard libraries.