Skip to content

Instantly share code, notes, and snippets.

@muromtsev
Created October 12, 2023 17:52
Show Gist options
  • Save muromtsev/2d95748bf449c3d4391a6ddf0d4ae531 to your computer and use it in GitHub Desktop.
Save muromtsev/2d95748bf449c3d4391a6ddf0d4ae531 to your computer and use it in GitHub Desktop.
binary_search
def binary_search(lst, item):
low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2
guess = lst[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 3)) # => 1
print(binary_search(my_list, -1)) # => None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment