Answer the question
In order to leave comments, you need to log in
Why does a binary search return None?
I am writing the binary search algorithm code from the book 'Groaking Algorithms'. Everything works, but it confuses me that the value None comes out when looking for a value in the array. Although this number is present in the array. How to fix it?
Here is what the code looks like -
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
elif guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1, 8, 4, 25, 14, 9, 3, 10]
print(binary_search(my_list, 14))
print(binary_search(my_list, 2))
print(binary_search(my_list, 8))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question