How do I find the median of numbers in linear time using heaps?

前端 未结 7 946
谎友^
谎友^ 2020-12-04 06:59

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

7条回答
  •  無奈伤痛
    2020-12-04 07:23

    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.

提交回复
热议问题