Stop looking at everything.
Exploit sorted order to shrink a search interval after every comparison.
01 The idea
Binary search maintains an interval that could contain a target. Comparing with its midpoint lets you discard approximately half of that interval. This gives logarithmic comparisons for sorted random-access data. The precondition matters: searching unsorted values with this algorithm can miss an item that is present.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def binary_search(values, target):
low, high = 0, len(values) - 1
while low <= high:
middle = (low + high) // 2
if values[middle] == target: return middle
if values[middle] < target: low = middle + 1
else: high = middle - 1
return -1
print(binary_search([3, 8, 12, 20, 31], 20))
print(binary_search([3, 8, 12, 20, 31], 7))3 -1
03 Under the hood
- 1
low and high describe an inclusive interval. Each update removes the midpoint because it has already been checked.
- 2
When low exceeds high, no candidate remains. Returning -1 is the example’s explicit not-found contract, not a Python indexing recommendation.
- 3
The bisect module finds insertion boundaries. bisect_left returns a possible position, so check the position is in range and equals the target before treating it as a successful search.
04 Your turn, builder
Use bisect_left to find 12 and report whether it is present.
Reveal one possible solution +
from bisect import bisect_left
values = [3, 8, 12, 20]
index = bisect_left(values, 12)
print(index < len(values) and values[index] == 12)05 Check your signal
What is a necessary precondition for this search?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.