← Back to Python, page 5

python-0086 · Medium mid

Implement binary search by hand and with the bisect module.

Binary search halves the search range each step, finding a value in a sorted list in O(log n). The hand-written version must handle the boundaries carefully. bisect.bisect_left gives the insertion point, which also answers 'how many items are smaller' and supports keeping a list sorted with insort.

Full answer
python
import bisect

def binary_search(items, target):
    lo, hi = 0, len(items) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

prices = [99, 149, 199, 249, 499, 999]
print(binary_search(prices, 249), binary_search(prices, 300))
i = bisect.bisect_left(prices, 300)
print(i, prices[i], i < len(prices) and prices[i] == 300)
grades = [(60, "D"), (70, "C"), (80, "B"), (90, "A")]
cut = [g[0] for g in grades]
print([("F" if (j := bisect.bisect_right(cut, s)) == 0 else grades[j - 1][1]) for s in [55, 70, 89, 95]])
bisect.insort(prices, 300)
print(prices)

Output:

text
3 -1
4 499 False
['F', 'C', 'B', 'A']
[99, 149, 199, 249, 300, 499, 999]

249 is found at index 3, and 300 is absent, so the hand-written search returns -1. bisect_left reports that 300 would go at index 4, before 499, which is a membership test when combined with a comparison. The grade lookup uses bisect_right on the cut-offs, so 70 counts as a C and anything below 60 is an F. insort inserts while keeping the list sorted, though each insert is O(n) because elements shift. Python 3.10 added a key parameter to bisect functions.

python
import bisect

def binary_search(items, target):
    lo, hi = 0, len(items) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

prices = [99, 149, 199, 249, 499, 999]
print(binary_search(prices, 249), binary_search(prices, 300))
i = bisect.bisect_left(prices, 300)
print(i, prices[i], i < len(prices) and prices[i] == 300)
grades = [(60, "D"), (70, "C"), (80, "B"), (90, "A")]
cut = [g[0] for g in grades]
print([("F" if (j := bisect.bisect_right(cut, s)) == 0 else grades[j - 1][1]) for s in [55, 70, 89, 95]])
bisect.insort(prices, 300)
print(prices)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Binary search is O(log n) on sorted data
  • Careful lo/hi boundaries
  • bisect_left gives insertion points
  • bisect_right for range lookups
  • insort keeps lists sorted

Common mistakes

  • Using binary search on unsorted data
  • Off-by-one errors in the loop condition

Follow-ups

  • How would you find the first index where a condition becomes true?
  • Why is insort O(n)?

Tips

  • Show a lookup table