Started reading a book about basic data structures and algorithms which uses this example code,
def binary_search(list, item):
low = 0
high = len(list)-1 #sets upper range to length of provided list
while low <= high:
mid = (low + high) #why does (low + high) give me middle of list?
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1,3,5,7,9]
print binary_search(my_list,3)
print binary_search(my_list,-1)
While I understand the concept of the tree I don't understand why
mid = (low + high) #why does (low + high) give me middle of list
?
wouldn't low + high just give me the same value as high? shouldn't i need low + high / 2 to find the midpoint? yet it works perfectly fine?
It works because mid
is always in the right range, but this is linear search, not binary. You can check this by printing the indices that are examined:
def binary_search(list, item):
low = 0
high = len(list)-1 #sets upper range to length of provided list
while low <= high:
mid = (low + high) #why does (low + high) give me middle of list?
print("mid =", mid)
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
Looking for -1 in your example:
>>> print (binary_search([1,3,5,7,9],-1))
mid = 4
mid = 3
mid = 2
mid = 1
mid = 0
None
So you are correct: you should divide mid
by 2 (and avoid using list
as a variable name).