Finding the median of an unsorted array

后端 未结 8 1107
后悔当初
后悔当初 2020-11-28 05:01

To find the median of an unsorted array, we can make a min-heap in O(nlogn) time for n elements, and then we can extract one by one n/2 elements to get the median. But this

8条回答
  •  清酒与你
    2020-11-28 05:49

    The quick select algorithm can find the k-th smallest element of an array in linear (O(n)) running time. Here is an implementation in python:

    import random
    
    def partition(L, v):
        smaller = []
        bigger = []
        for val in L:
            if val < v: smaller += [val]
            if val > v: bigger += [val]
        return (smaller, [v], bigger)
    
    def top_k(L, k):
        v = L[random.randrange(len(L))]
        (left, middle, right) = partition(L, v)
        # middle used below (in place of [v]) for clarity
        if len(left) == k:   return left
        if len(left)+1 == k: return left + middle
        if len(left) > k:    return top_k(left, k)
        return left + middle + top_k(right, k - len(left) - len(middle))
    
    def median(L):
        n = len(L)
        l = top_k(L, n / 2 + 1)
        return max(l)
    

提交回复
热议问题