0

I am making a binary search program to search a number in a list. Below is the current program. I require the program to find a the index of a number if it is found in the list, otherwise, it should return "not found".

But the code below does not exit out of the loop if the number is not found. How can I make it do so ?

def binary_search(n):
    l = [1,6,7,10,19,24,42,81]
    low = 0
    high = len(s)-1
    index = (high + low)/2
    while s[index] != n:
        if s[index] < n:
            low = index + 1
        else:
            high = index
        index = (high + low)/2

binary_search(43)

I have tried adding

if index == None:
    print "Not Found"
else:
    print index

before the function call, but as I said, the loop does not exit if it cannot find the number.

2
  • Have you tried using an if-statement inside it and then break when it matches those conditions? Commented Jun 24, 2015 at 2:57
  • Yes, I tried adding break, but it gives me the result as 5 even when its not found. I gives me the location just before the least greatest number. Commented Jun 24, 2015 at 2:59

2 Answers 2

1

You need to break the while loop in case there is no element. You can add a condition like this:

while s[index] != n:
    if low>=high:
        return "Not Found"
    if  s[index] < n:
        low = index + 1 
    else:
        high = index
    index = (high + low)/2

Or change the condition for the while loop.

while low<high:
    if l[index] == n:
        print index
    if  l[index] < n:
        low = index + 1 
    else:
        high = index
    index = (high + low)/2
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Your edit is great but how can I print not found now, since there is no condition?
that is too easy. one way is not printing but returning from the loop using return index instead of print index and from the binary_search function return "Not Found". @WhiteFlameAB also why did you unaccepted the answer after accepting it?
1

It is because of the condition of the while loop. The loop goes on until it finds the element in the list. So when the element is not in the list, the loop won't break. You can debug the code by printing the values of high, low and index in each iteration.

To confirm that the element is not in the list, you can check another condition. When low >= high is true, it means that the search range is empty, thus the element is not present in the list.

Comments

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.