Why does binary search algorithm not work?

Question:

I’ve copied code from the book "grokking algorithms" for finding an item in the list using the binary search algorithm. The code launches great and returns no errors. However, sometimes it just doesn’t work for certain numbers, for example if i call it to find "1". What’s wrong?

def binary_search(list, item):
    low = 0
    high = len(list) - 1

    while low <= high:
        mid = (low + high)/2
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid + 1
        else:
            low = mid + 1
    return None

list1 = []

for i in range (1, 101):
    list1.append(i)

print(list1)
print(binary_search(list1, 1))
Asked By: ela rednax

||

Answers:

Two issues:

  • Use integer division (so it will work in Python 3): mid = (low + high)//2

  • When guess > item you want to exclude the guessed value from the next range, but with high = mid + 1 it still is in the range. Correct to high = mid - 1

Answered By: trincot

Still does not work properly with both mentioned errors corrected, the following code returns None two times. What could be the problem?

def binary_search (lst, item):
    low=0
    high=len(lst)-1
    while low <= high:
        mid=(low+high)//2
        guess=lst[mid]
        if guess==item:
            return guess
        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))
Answered By: Marsel Shafikov