Halving the Search: Classic Binary Search
A raffle has sold a million tickets, and their numbers are stored in sorted order. Someone asks whether ticket 730,512 was sold. Reading the list from the start could take a million checks. Opening it in the middle, seeing which half the number must be in, and repeating takes about twenty.
The rule
Sorted? Check the middle and throw away the half that cannot hold it.
Keep two bounds, lo and hi, around the part of the list that could still contain the target. Look at the middle item. If it is the target, you are done. If it is too small, the target can only be to its right; if too big, only to its left. Either way, half the remaining list is gone after one comparison.
def find(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi: # the window still holds at least one item
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1 # target can only be right of mid
else:
hi = mid - 1 # target can only be left of mid
return -1The idea that keeps this correct is an invariant, a promise that is true before every loop: if the target is in the list at all, it lies between lo and hi. Every update keeps the promise, and when lo passes hi the window is empty, so the target is not there. The + 1 and - 1 matter too: mid has already been checked, so it leaves the window.