Search code examples
pythonarraysbinary-search

What is wrong with this python binary search code, im getting an index error


I keep getting an index overflow error. Am i missing something? I checked my array length again and again but i dont see where i have accessed a value which does not exist

def binary_search_helper(arr,val,low,high):
    
    mid = low + ((low+high)//2)

    if low >= high:
        return("Not F")
    
    elif val==arr[mid] :
        return (arr[mid])
    
    elif val<=arr[mid]:
        return( binary_search_helper(arr, val, low, mid-1))

    else:
        return( binary_search_helper(arr, val, mid+1, high))
    

def binary_search(arr,val):
    return binary_search_helper(arr, val, 0, len(arr)-1)


if __name__=="__main__":
    arr=[0,1,2,3,4,5]
    val=3

    ans= binary_search(arr,val)
    print(ans)

Solution

  • There are several mistakes, you can look what I changed here:

    def binary_search_helper(arr,val,low,high):
        
        mid = (low+high)//2
    
        if val==arr[mid] :
            return (arr[mid])
        
        elif low >= high:
            return("Not F")
            
        elif val<=arr[mid]:
            return( binary_search_helper(arr, val, low, mid-1))
    
        else:
            return( binary_search_helper(arr, val, mid+1, high))