10/41
Part 2 of 7 · Binary searchLearn
Two bounds keep two promises, and each look moves one of them past the middle
Here are the times a setting changed, sorted. An incident started at 250. How many changes came before it, and which change came next?
Both answers are one index: the first position whose time is at least 250. A scan from the left looks at every time up to it, O(n). Binary search uses the order to throw away half of what's left with each look:
def first_at_or_after(times, target):
lo, hi = 0, len(times)
while lo < hi:
mid = (lo + hi) // 2
if times[mid] < target:
# mid and everything before it are below the target
lo = mid + 1
else:
# mid and everything after it are at least the target
hi = mid
return lo
times = [100, 130, 160, 220, 300, 410, 520, 600]
print(first_at_or_after(times, 250))
8 sorted times, and the target is 250. How many looks does binary search take to find the first time at or after it?
Pick one to see what it prints.
Pick an answer above to see the rest