A selection algorithm that uses array partitioning around a pivot and recursively searches only the side containing the desired order statistic. If there are entries before the placed pivot, an earlier rank is unchanged and a later rank is reduced by . Segment length strictly decreases, proving algorithm termination. The same reduction can update local bounds in a loop, using constant auxiliary space.
Balanced reductions give linear work by a geometric series, while repeatedly discarding only a constant number of entries can give quadratic work. For distinct entries and independent uniform random pivots, a pivot in the middle half has probability at least one half and reduces the retained length to at most three quarters, up to rounding. The expected number of attempts for each such reduction is bounded, so summing expected work over geometric size scales gives expected time. This random-pivot guarantee is not a worst-case guarantee for a deterministic median-of-three heuristic. With duplicates and a strict two-way partition, random pivot choice alone can also fail to shrink an all-equal segment; a three-way partition treats equal keys together.
Choose the median value among the first, middle and last entries of an active array segment. For at least three distinct sampled values, the selected value cannot be the whole segment's minimum or maximum. It can still be the second-smallest or second-largest value, so a balanced split does not follow. Coincident sample indices in segments of length one or two can be handled by the same comparison code. Ties must also have a defined branch policy.
A distinct-input counterexample for Quickselect that chooses the first/middle/last median, reserves it at the last slot, scans lower values to the front, and finally swaps the pivot into place. Let be the following permutation of . For , take increasing order. For , let componentwise and , then setand put at every other index . These assignments use every entry of once and add zero and one, so they really define a permutation.
The sampled values are , with the last at least two, so the pivot is one. After the initial pivot swap, the only lower value is the zero at index . Moving it to the front places the displaced at its intended tail position. The final pivot swap moves from index one to the last position. Every other tail entry already has its intended position. Thus the complete partitioned result is exactly followed by .
Selecting the maximum consequently repeats the same construction on entries. If counts only pivot comparisons made by the partition scan, then , with and . Hence and total runtime is . For example, . This disproves a linear worst-case claim even when every value is distinct.
Articles by others on the same topic
Quickselect is an efficient algorithm used to find the k-th smallest (or largest) element in an unordered list. It is related to the Quicksort sorting algorithm and uses a similar partitioning approach.