In a sorted list, look at the middle and throw away the half that cannot contain the target. Ten items take only three checks.
Python · intermediate · 7 min · 19 steps · free
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
sorted_nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(binary_search(sorted_nums, 23))binary_search(). Its body does not run yet: it runs each time the function is called.sorted_nums is created and points to a new list: [2, 5, 8, 12, 16, 23, 38, 56, …].binary_search(), with items = [2, 5, 8, 12, 16, 23, 38, 56, …] and target = 23. It gets its own names.low and high mark the part of the list where 23 could still be: all of it.low <= high is true, so the loop body runs.items[mid] == target is false, so the block under it is skipped.items[mid] < target is true, so the block under it runs.low <= high is true, so the loop body runs.mid changes from 4 to 7.items[mid] == target is false, so the block under it is skipped.items[mid] < target is false, so the block under it is skipped.low <= high is true, so the loop body runs.mid changes from 7 to 5.items[mid] == target is true, so the block under it runs.binary_search() has finished, so its names are gone. It prints 5.Answer: 10. 2¹⁰ = 1024.
Answer: high = mid - 1
← Linear Search · Two Pointers →