Sorting a list answers every order question at once — but it is also overkill. If you only need the k-th smallest element (the median, the 90th percentile, the second-largest), sorting is doing far more work than necessary.
The naive remedy is quickselect: partition the array around a pivot, then recurse only into the half that contains rank k. On random data this runs in expected time. But a malicious input — or even an unlucky pivot choice — can degrade it to . For a long time it was an open question: can you find the k-th smallest element in guaranteed time, without sorting?
In 1973, Manuel Blum, Robert Floyd, Vaughan Pratt, Ronald Rivest, and Robert Tarjan (BFPRT) answered yes. Their algorithm — now called median of medians — selects a pivot so carefully that the array is always split into at least a constant fraction on each side, guaranteeing worst-case time no matter what the input looks like.
The idea is beautifully recursive: to find a good pivot for selecting from n elements, first find the exact median of a smaller set derived from n — and that smaller selection problem is solved by the same algorithm.
Comments
Loading comments...