user16986234
user16986234

Reputation: 1

what is wrong with my binary search python code

I am constantly getting the wrong output in my binary search program. The output is always None even when the key element is present. Have a look at my code and help, please.

guess=1
def binary_search(n,key):
    low=0
    high=len(n)-1
    
    while(low <= high):
        mid=(low+high)//2
        guess=n[mid]
        if(guess==key):
            return mid
        elif (guess<key):
            high=mid-1
        elif(guess>key):
            low=mid+1
    return None

n=[1,3,5,7,9]
print(binary_search(n,3)) 

Upvotes: 0

Views: 253

Answers (1)

Albin Paul
Albin Paul

Reputation: 3419

Your search conditions are wrong. if guess>key then you need to decrease the guess my setting high=mid-1 and increase the guess with low=mid+1 if guess<key.

guess=1
def binary_search(n,key):
    low=0
    high=len(n)-1
    
    while(low <= high):
        mid=(low+high)//2
        guess=n[mid]
        if(guess==key):
            return mid
        elif (guess>key):
            high=mid-1
        elif(guess<key):
            low=mid+1
    return None

n=[1,3,5,7,9]
print(binary_search(n,3))

Upvotes: 4

Related Questions