D
D
dyrtage62020-07-24 21:58:40
Python
dyrtage6, 2020-07-24 21:58:40

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))


Here is what the console outputs (the first value should give the index, but for some reason it outputs None) -
5f1b2f27a9b33949583352.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-07-24
@dyrtage6

Binary search only works on an ordered array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question