Wikipedia says:
Selection algorithms: Finding the min, max, both the min and max, median, or even the k-th largest element can be done i
There are likely better algorithms out there, but here's how I'd do it:
Have two buckets and a value. The value is the median, the two buckets are "bigger than median" and "smaller than median". For each element x
in the array, rebalance the buckets such that big_bucket
and small_bucket
differ by no more than 1 in their size. When moving items from the big bucket to the small bucket they first must pass through the median value to get there (that is, a difference of 2 will successfully push an element from one bucket to the next - a difference of 1 will push an element from one bucket to the median value.) At the end of your first pass through the array the value should be your median.