I am beginner in programming. I am reading the book "Grokking algorithms" by Aditya Y Bhargava." And in the first code I found a mistake. The book describes binary algorithm. It says that the algorithm must takes the average of an array and then average of that average, but I debbuged the code and it just takes a very big number of array and then reduces it by 1. Maybe it is a difference between versions, because I use Python 3.7, but in the book it is Python 2.7
def binary_search(list, item):
low = 0
high = len(list)-1
while low <= high:
mid = int(low + high)
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(binary_search(my_list, 1))
The errata for the book lists this as an error. It should be:
mid = (low + high) // 2
So: good catch!
And, spoiler alert: there are more errors!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With