-3

I saw a similar question on stack overflow that was asked 5 months ago but it wasn't answered. It's a simple binary search algorithm but I don't understand why the function is returning None instead of the index where the element is

def binary_search(arr,hi,low,x):
    if(hi>=low):
        mid=(hi+low)//2
        if arr[mid]==x:
            print(mid)
            return mid
        elif(arr[mid]>x):
            binary_search(arr,mid-1,low,x)
        else:
            binary_search(arr,hi,mid+1,x)
    else:
        return -1
arr=[4,3,9,10,23,7,9]
x=3
y=binary_search(arr,len(arr)-1,0,x)
print(str(y))

It's printing 1 as mid inside the binary_search function but when I print the result, y. Im getting None.

1 Answers1

1

For your lines that recursively call binary_search, you're not returning anything. You need to pass the return of recursive calls up the stack for this implementation. Add a return before each of these lines.

Jeremy
  • 661
  • 7
  • 19