Created
October 12, 2023 17:52
-
-
Save muromtsev/2d95748bf449c3d4391a6ddf0d4ae531 to your computer and use it in GitHub Desktop.
binary_search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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