Binary Search Algorithm

By Salerno | December 28, 2019


def binary_search(lista, item):
  low = 0 # low and high are part of the list thar you are searching for
  high = len(lista) - 1
  
  while low <= high: #while you are not achieving one unique element
    middle = (low + high) // 2 # checking the central element
    guess = lista[middle]
    if guess == item:
      return middle
    if guess > item: # the guess are too high
      high = middle - 1
    else: # the guess are too low
      low = middle + 1
  return None
  
my_list = [1, 3, 5, 7, 9]
  
print(binary_search(my_list, 3))
## 1
print(binary_search(my_list, -1))
## None
comments powered by Disqus