Python implementation of “median of medians” algorithm

前端 未结 2 1634
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 08:49

I\'ve written this implementation of the median of medians algorithm in python, but it doesn\'t seem to output the right result, and it also does not seem of linear complexi

2条回答
  •  爱一瞬间的悲伤
    2020-12-06 09:20

    1) Your code indentation is wrong, try this:

    def select(L):
        if len(L) < 10:
            L.sort()
            return L[int(len(L)/2)]
        S = []
        lIndex = 0
        while lIndex+5 < len(L)-1:
            S.append(L[lIndex:lIndex+5])
            lIndex += 5
        S.append(L[lIndex:])
        Meds = []
        for subList in S:
            print(subList)
            Meds.append(select(subList))
        L2 = select(Meds)
        L1 = L3 = []
        for i in L:
            if i < L2:
                L1.append(i)
            if i > L2:
                L3.append(i)
        if len(L) < len(L1):
            return select(L1)
        elif len(L) > len(L1) + 1:
            return select(L3)
        else:
            return L2
    

    2) The method you use does not return the median, it just return a number which is not so far from the median. To get the median, you need to count how many number are greater than your pseudo-median, if a majority is greater, repeat the algorithm with the numbers greater than the pseudo-median, else repeat with the other numbers.

    def select(L, j):
        if len(L) < 10:
            L.sort()
            return L[j]
        S = []
        lIndex = 0
        while lIndex+5 < len(L)-1:
            S.append(L[lIndex:lIndex+5])
            lIndex += 5
        S.append(L[lIndex:])
        Meds = []
        for subList in S:
            Meds.append(select(subList, int((len(subList)-1)/2)))
        med = select(Meds, int((len(Meds)-1)/2))
        L1 = []
        L2 = []
        L3 = []
        for i in L:
            if i < med:
                L1.append(i)
            elif i > med:
                L3.append(i)
            else:
                L2.append(i)
        if j < len(L1):
            return select(L1, j)
        elif j < len(L2) + len(L1):
            return L2[0]
        else:
            return select(L3, j-len(L1)-len(L2))
    

    Warning: L = M = [] is not L = [] and M = []

提交回复
热议问题