Search code examples
python-3.xrecursionbinary-search

Binary Search function returning None value in python


Below is the code which I used for binary search in python using recursion. I have not used num == l[mid] since this is being handled by function calling this binarySearch. I just have to return the last item of list being left while splitting it.

def binarySearch(l,num):
    length = len(l)
    
    if length==1:
        print(l)
        return l

    if length % 2 == 0:
        mid = (length//2) - 1
    else:
        mid = length//2
        
    if num < l[mid]:
        binarySearch(l[mid+1:],num)
    else:
        binarySearch(l[0:mid+1],num)

print(l) prints the correct value which I want to return but return l gives me None instead of l


Solution

  • if num < l[mid]: binarySearch(l[mid+1:],num) doesn't return anything: it calls binarySearch and discards its return value. Thus, None is returned implicitly. You should actually return the values you want to be returned:

    if num < l[mid]:
        return binarySearch(l[mid+1:],num)
    else:
        return binarySearch(l[0:mid+1],num)
    

    Here, return binarySearch(...) means "return whatever the call to binarySearch returned".