O(n) algorithm to find the median of n² implicit numbers

There are a number of possibilities. One I like is Hoare’s Select algorithm. The basic idea is similar to a Quicksort, except that when you recurse, you only recurse into the partition that will hold the number(s) you’re looking for.

For example, if you want the median of 100 numbers, you’d start by partitioning the array, just like in Quicksort. You’d get two partitions — one of which contains the 50th element. Recursively carry out your selection in that partition. Continue until your partition contains only one element, which will be the median (and note that you can do the same for another element of your choice).

Leave a Comment