Is it possible to calculate median of a list of numbers better than O(n log n)?

前端 未结 7 914
攒了一身酷
攒了一身酷 2021-02-14 04:30

I know that it is possible to calculate the mean of a list of numbers in O(n). But what about the median? Is there any better algorithm than sort (O(n log n)) and lookup middl

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 04:37

    If the numbers are discrete (e.g. integers) and there is a manageable number of distinct values, you can use a "bucket sort" which is O(N), then iterate over the buckets to figure out which bucket holds the median. The complete calculation is O(N) in time and O(B) in space.

提交回复
热议问题