Created
February 19, 2019 14:55
-
-
Save pysoftware/1def6de9d0ae63ac29835d032e6fe05b to your computer and use it in GitHub Desktop.
Binary search
This file contains hidden or 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
# Binary search/ бинарная сортировка | |
def binary_search(list, item): | |
# В переменных low и high хранятся | |
# границы той части списка, в которой | |
# выполняется поиск | |
low = 0 | |
high = len(list) - 1 | |
i = 0 | |
while low <= high: | |
i += 1 | |
mid = (low + high) // 2 | |
guess = list[mid] | |
if guess == item: | |
print(i) | |
return mid | |
if guess > item: | |
high = mid - 1 | |
else: | |
low = mid + 1 | |
return None | |
test_list = [1,3,5,7,9] | |
print(binary_search(test_list,9)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment