Skip to content

Instantly share code, notes, and snippets.

@pysoftware
Created February 19, 2019 14:55
Show Gist options
  • Save pysoftware/1def6de9d0ae63ac29835d032e6fe05b to your computer and use it in GitHub Desktop.
Save pysoftware/1def6de9d0ae63ac29835d032e6fe05b to your computer and use it in GitHub Desktop.
Binary search
# 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