main algorithms/lessons/05-binary-search/binary_search.py

19 lines479 B

def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
if __name__ == "__main__":
data = [3, 8, 15, 23, 42, 57, 91]
print(binary_search(data, 42)) # 4
print(binary_search(data, 5)) # -1
# Try changing the values above and run it again.