Search code examples
python-3.xmediandivide-and-conquer

Median of sorted arrays of equal length


I am trying to find the median of two sorted array of same length for this I am using divide and conquer algorithm. But my code returns None instead of a value Here is code to find median of single array:

def getmedian(li):
    x = len(li)
    if x%2 == 0:
        return (li[x//2] + li[(x//2)-1])/2
    else:
        return li[(len(li)-1)//2]

and then I'm using following function for two arrays:

def TwoList(list1,list2):
    if len(list1) == 1:
        return (list1[0] + list2[0])/2
    elif len(list2)== 2:
        return (max(list1[0],list2[0]) + min(list2[1], list1[1]))/2
    else:
        #pdb.set_trace()
        x = getmedian(list1)
        y = getmedian(list2)
        if x == y:
            return x
        elif x > y:
            if len(list1)%2==0:
                TwoList(list1[:len(list1)//2], list2[len(list1)//2:])
            else:
                TwoList(list1[:len(list1)//2+1], list2[len(list1)//2:])
        else:
            if len(list1)%2==0:
                TwoList(list1[len(list1)//2:], list2[:len(list1)//2])
            else:
                TwoList(list1[len(list1)//2:], list2[:len(list1)//2+1])

Solution

  • Looks like you are doing it right except returning value in TwoList recursive calls.
    Please see below code, commented where you have to return value.

    def getmedian(li):
        x = len(li)
        if x%2 == 0:
            return (li[x//2] + li[(x//2)-1])/2
        else:
            return li[(len(li)-1)//2]
    
    def TwoList(list1,list2):
        if len(list1) == 1:
            return (list1[0] + list2[0])/2
        elif len(list2)== 2:
            return (max(list1[0],list2[0]) + min(list2[1], list1[1]))/2
        else:
            #pdb.set_trace()
            x = getmedian(list1)
            y = getmedian(list2)
            if x == y:
                return x
            elif x > y:
                if len(list1)%2==0:
                    return TwoList(list1[:len(list1)//2], list2[len(list1)//2:]) # return value
                else:
                    return TwoList(list1[:len(list1)//2+1], list2[len(list1)//2:]) # return value
            else:
                if len(list1)%2==0:
                    return TwoList(list1[len(list1)//2:], list2[:len(list1)//2]) # return value
                else:
                    return TwoList(list1[len(list1)//2:], list2[:len(list1)//2+1]) # return value
    
    print(TwoList([1,2,3,4],[5,6,7,8]))