-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
  • The code needs to return the value that is returned from the recursive call, i.e. return binary_search(...) Commented Aug 4, 2020 at 17:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.