Rocket wants the halving search built into the catalog panel. He types fast and stops at two lines.
"When the target is bigger, I move low," he says. "But to where? To mid?"
Raven points at the middle spot. "What do you notice about mid after we check it?"
"It is not the target, so we never need it again!" Rocket says.
Nova blinks. "Here is a hint. Move one spot past mid, in the right direction."
def binary_search(items, target):
low = 0
high = 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
ids = [3, 8, 12, 15, 21, 27, 30, 36]
print(binary_search(ids, 27))
print(binary_search(ids, 10)) Output: 5 -1
def binary_search(items, target):
low = 0
high = len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
low = ____
else:
high = ____
return -1
print(binary_search([3, 8, 12, 15, 21, 27, 30, 36], 30)) def binary_search(items, target):
low = 0
high = 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
ids = [4, 9, 13, 18, 22]
print(binary_search(ids, 4))
print(binary_search(ids, 22))
print(binary_search(ids, 5)) | Statement | True or false? |
|---|---|
| The first mid for ids is spot 2. | ? |
| binary_search returns the target itself. | ? |
| Searching for 4 checks spot 2, then spot 0. | ? |
| return -1 runs when low passes high. | ? |
Great reading! Binary search is short, but every line matters. Tomorrow we count its checks on bigger lists.