Binary Search
Medium · 55 XPImplement binary search returning the index of a target in a sorted list, or -1. Print the index for four targets and the number of comparisons for one of them.
0 4 9 -1
Keep lo and hi bounds; compare the middle and discard half each step.
def binary_search(values, target):
lo, hi = 0, len(values) - 1
while lo <= hi:
mid = (lo + hi) // 2
if values[mid] == target:
return mid
if values[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
values = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
for t in (1, 9, 19, 8):
print(binary_search(values, t))
Run your code to check it…
How to approach Binary Search
Binary search works on sorted data by halving the search space at every step. Keep two bounds, lo and hi, look at the middle element, and throw away the half that cannot contain the target.
If the middle value is too small, the target must be to its right, so move lo to mid + 1. If it is too big, move hi to mid - 1. Loop while lo <= hi; when the bounds cross, the target is not there and you return -1.
Worked through on this data
- Searching for 9 in the ten values: lo = 0, hi = 9, mid = 4, and values[4] is 9. Found on the first comparison: index 4.
- Searching for 8: mid = 4 (9 is too big, so hi = 3), then mid = 1 (3 is too small, so lo = 2), then mid = 2 (5, lo = 3), then mid = 3 (7, lo = 4).
- Now lo = 4 is greater than hi = 3, so 8 is not in the list: -1. 1 and 19 are found at indices 0 and 9.
Common mistakes
- Looping
while lo < hiskips the last remaining candidate, so a target in the final position can be missed. - Setting
lo = midinstead ofmid + 1can loop forever when lo and hi are next to each other. - Running it on unsorted data returns wrong answers silently, with no error.
Time and space
Each step halves the range, so it is O(log n) time and O(1) space. A million sorted items need at most 20 comparisons; a linear scan might need a million.
Where this shows up
Database indexes, git bisect hunting the commit that broke a build, and Python's own bisect module all rest on this halving idea.
Take it further
Count the comparisons each search makes and print them, then compare your results with bisect.bisect_left from the standard library.