Find the median of an unsorted array without sorting

Monica picture Monica · Nov 27, 2015 · Viewed 28.3k times · Source

is there a way to find the Median of an unsorted array: 1- without sorting it. 2- without using the select algorithm, nor the median of medians

I found a lot of other questions similar to mine. But the solutions, most of them, if not all of them, discussed the SelectProblem and the MedianOfMedians

Answer

rici picture rici · Nov 27, 2015

You can certainly find the median of an array without sorting it. What is not easy is doing that efficiently.

For example, you could just iterate over the elements of the array; for each element, count the number of elements less than and equal to it, until you find a value with the correct count. That will be O(n2) time but only O(1) space.

Or you could use a min heap whose size is just over half the size of the array. (That is, if the array has 2k or 2k+1 elements, then the heap should have k+1 elements.) Build the heap using the first array elements, using the standard heap building algorithm (which is O(N)). Then, for each remaining element x, if x is greater than the heap's minimum, replace the min element with x and do a SiftUp operation (which is O(log N)). At the end, the median is either the heap's minimum element (if the original array's size was odd) or is the average of the two smallest elements in the heap. So that's a total of O(n log n) time, and O(n) space if you cannot rearrange array elements. (If you can rearrange array elements, you can do this in-place.)