Python binary search
Binary search requires input sorted in ascending order under the same comparison used by the search. The inclusive interval [low, high] contains every remaining candidate.
Python
def binary_search(values, target):
low, high = 0, len(values) - 1
while low <= high:
mid = low + (high - low) // 2
if values[mid] == target:
return mid
if values[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([2, 4, 6, 8, 10], 8))
print(binary_search([2, 4, 6, 8, 10], 7))
assert binary_search([], 1) == -1
assert binary_search([2], 2) == 0