0

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)) 
3
  • 1
    @Old_Arrack not true: return mid Commented Sep 23, 2021 at 15:49
  • @2e0byo Oh yeah, I'm really sorry I didn't see it. Commented Sep 23, 2021 at 15:54
  • I literally opened an answer to type exactly the same thing... Commented Sep 23, 2021 at 15:55

1 Answer 1

4

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))
Sign up to request clarification or add additional context in comments.

4 Comments

In other words, they need to swap + and - or < and >?
@MisterMiyagi that wouldnt work. setting high=mid+1 doesnt make sense. if key < mid then high = mid - 1 else low = mid+1.
So the second case, they need to swap the < and >?
@MisterMiyagi Yes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.