How quickselect finds one order statistic

Short answer: Quickselect partitions around a pivot and recurses into the only side that still contains rank k. A partition that places the pivot at its final index answers immediately when that index equals k. The expected cost with a random pivot is Θ(n). A pivot that always leaves k on a side of length n−1 costs Θ(n²). The algorithm returns one order statistic, not a sorted array.


What the problem actually asks

The k-th smallest key is the key that would sit at index k after a full sort, counting from zero. Sorting computes every other rank as well. After a partition, the pivot’s final index p is its rank. If p = k the pivot is the answer. If k < p every key at or to the right of p is too large, and the answer lies in the left slice. Otherwise it lies in the right slice.

That discard needs a partition that actually places the pivot. Hoare’s partition returns a cut, and the pivot value may sit on either side of the cut, so the rank test p = k is not available.


What the algorithm guarantees

With a uniformly random pivot, the expected number of comparisons is linear in n. A standard bound is at most 4n for the average over pivots, up to lower-order terms; the exact constant depends on the partition. The worst case remains Θ(n²), the same one-sided recursion as quicksort. Extra memory is the recursion stack, which can be held to O(log n) expected by iterating and, if desired, recursing in a way that does not stack both sides. Only one side exists here, so the loop is naturally iterative.

The result is the key of rank k, and the array is rearranged so that every index below the final pivot position holds a key ≤ that key. The order inside each side is otherwise unspecified. Equal keys make the rank any index of that key’s run, depending on how the partition buckets equals.


The working steps

  1. Ask for rank k with 0 ≤ k < n. Shuffle the array, or choose a random pivot index at each step.
  2. Partition so the chosen pivot ends at an index p, with keys before p ≤ the pivot and keys after p ≥ the pivot. Lomuto’s partition does this. Hoare’s cut does not.
  3. If p = k, return the pivot. If k < p, repeat on [lo, p). Otherwise repeat on (p, hi].
  4. A median-of-three pivot reduces the chance of a one-sided split and does not by itself turn the worst case into a linear bound.
  5. When a hard linear worst case is required, choose the pivot with median of medians instead of at random.

Expected linear time selects one rank. It does not sort. Calling quickselect once per rank reintroduces an n log n sort with a worse constant. A worst-case linear selection is median of medians, which is this recursion with a more expensive pivot.


Approaches that look simpler and fail

Approach Why it fails when the pivot is not placed at its rank
Hoare’s partition, then test the cut index against k The cut is not the pivot’s rank. The answer can lie on either side, and excluding the cut drops a candidate.
Sort the array and index it The k-th key comes back, after Θ(n log n) work. The partition discards a side so that those keys are never sorted.
A fixed end pivot on a sorted array Each partition removes one item. Selecting the median then copies n²/4 comparisons.
Assume the expected linear bound is a deadline An adversary who sees the pivot rule can force the long side to contain k every time. Randomness, or median of medians, is what blocks that adversary.

Worst-case linear selection belongs to median of medians. A full ordering belongs to a sort. The partition primitive is the same one quicksort uses, and only the placed-pivot form serves this rank test.


A working example

The Bash script and the Python script quickselect with a partition that places the pivot. They return the element of rank 3 in zero-based order, which is 4.

a=(7 2 1 8 6 3 5 4)
k=3
lo=0
hi=${#a[@]}
while (( hi - lo > 1 )); do
  pivot=${a[hi-1]}
  i=$lo
  for ((j=lo; j<hi-1; j++)); do
    if (( a[j] < pivot )); then
      t=${a[i]}; a[i]=${a[j]}; a[j]=$t
      i=$((i+1))
    fi
  done
  t=${a[i]}; a[i]=${a[hi-1]}; a[hi-1]=$t
  if (( i == k )); then break; fi
  if (( k < i )); then hi=$i; else lo=$((i+1)); fi
done
echo "${a[k]}"
def quickselect(a, k):
    a = a[:]
    lo, hi = 0, len(a)
    while hi - lo > 1:
        pivot = a[hi - 1]
        i = lo
        for j in range(lo, hi - 1):
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi - 1] = a[hi - 1], a[i]
        if i == k:
            return a[i]
        if k < i:
            hi = i
        else:
            lo = i + 1
    return a[lo]

data = [7, 2, 1, 8, 6, 3, 5, 4]
assert quickselect(data, 3) == sorted(data)[3] == 4
print(quickselect(data, 3))

Where it is used

C++ nth_element and database percentiles use quickselect, or introselect wrapped around it, to find one order statistic without sorting the rest. A median filter and a top-k threshold are the same call. A full sort is wasted work when only the k-th key is required.


When you can drop this algorithm

Drop quickselect when the worst case must be linear. Median of medians pays a large constant for that proof. Drop it when every rank is needed. A sort is then simpler. Keep random-pivot quickselect when one order statistic is required and an expected linear scan of the array is the right budget.


Why this stays published

We publish this so a search for quickselect returns the placed pivot and the expected linear cost of following only the side that holds rank k. Quickselect partitions until the pivot lands on the requested rank, which takes expected linear time and can take quadratic time if the pivot is always at the end.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *