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.
breakwhen it matches those conditions?