33/40
Part 8 of 8 · Follow-upsLearn and do

Only one k-th item, once? Quickselect, O(n) on average when the values are distinct

Quicksort picks a pivot, moves the smaller items to its left and the rest to its right, then sorts each side. Quickselect does the same split around a random pivot, then keeps only the side that holds position k. The booksite frames the median as a special case of this: selection, finding the k-th smallest of a set of numbers.

import random


# k-th smallest, k counted from 0
def quickselect(items, k):
    items = list(items)
    lo, hi = 0, len(items) - 1
    rng = random.Random(0)
    while True:
        if lo == hi:
            return items[lo]
        p = rng.randint(lo, hi)
        items[p], items[hi] = items[hi], items[p]
        pivot, store = items[hi], lo
        # smaller than the pivot to the left
        for i in range(lo, hi):
            if items[i] < pivot:
                items[i], items[store] = items[store], items[i]
                store += 1
        items[store], items[hi] = items[hi], items[store]
        if k == store:
            return items[k]
        if k < store:
            hi = store - 1
        else:
            lo = store + 1


print(quickselect([30, 12, 45, 7, 21, 18, 60], 3))
21

It's O(n) on average on distinct values, because each round keeps one side and the sides shrink geometrically. It's O(n²) in the worst case, which a random pivot makes unlikely.

Repeats break that. An item equal to the pivot never goes left. On 8,000 equal values, each round shrinks the range by one, and the median took 24 million comparisons, four times as many as on 4,000. That's quadratic whatever the pivot. With many repeats, split into less, equal and greater, and stop when k lands in the equal block.

For the median of a million random floats, this plain Python took about 150 ms on a typical input (70 to 205 ms over 20 inputs). That's no faster than sorted(d)[k] at about 140 ms, because the sort runs in C. heapq.nsmallest(k + 1, d)[-1] took 984 ms. A heap of size k is the wrong tool when k is half of n.

In the editor, write select(items, k): quickselect with a three-way split into less, equal and greater, so a list full of repeats can't make it quadratic.