Find the Running Median

  • + 0 comments
    def bisect_insort(arr, n):
        i, j = 0, len(arr) - 1
        while i <= j:
            m = (i + j)//2
            if arr[m] > n:
                j = m - 1
            elif arr[m] < n:
                i = m + 1
            else:
                i = m
                break
        arr.insert(i, n)
            
    def runningMedian(a):
        medians = []
        arr = []
    		
        for i, n in enumerate(a, 1):
            # bisection
            bisect_insort(arr, n)
            
            # median
            m = i // 2
            if i % 2:
                medians.append(round(arr[m], 1))
            else:
                medians.append(round((arr[m] + arr[m-1]) / 2, 1))
                
        return medians