Reputation: 113
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))
Upvotes: 11
Views: 2961
Reputation: 3031
Yes, I have just started reading this book and stumbled upon this issue. Basically, there are 2 errors:
In the book where it first shows an example of getting average it is:
mid = (low + high) / 2 #Should be mid = (low + high) // 2
/
- Division (float): divides the first operand by the second
//
- Division (floor): divides the first operand by the second
And second error as it was already answered:
mid = (low + high) #Should be mid = (low + high) // 2
More errors at https://adit.io/errata.html
Upvotes: 3
Reputation: 8152
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!
Upvotes: 15