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

前端 未结 7 915
攒了一身酷
攒了一身酷 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:38

    Partially irrelevant, but: a quick tip on how to quickly find answers to common basic questions like this on the web.

    • We're talking about medians? So Gg to the page about medians in wikipedia
    • Search page for algorithm:

    Efficient computation of the sample median

    Even though sorting n items takes in general O(n log n) operations, by using a "divide and conquer" algorithm the median of n items can be computed with only O(n) operations (in fact, you can always find the k-th element of a list of values with this method; this is called the selection problem).

    • Follow the link to the selection problem for the description of algorithm. Read intro:

    ... There are worst-case linear time selection algorithms. ...

    • And if you're interested read about the actual ingenious algorithm.

提交回复
热议问题