Algorithms

Why binary search gets stuck on two numbers

If binary search keeps checking the same number, inspect the update that runs after a failed comparison. With inclusive bounds and a midpoint rounded down, lo = mid can leave both ends of the search exactly where they started.

Trace the smallest input that gets stuck

Look for 9 in the sorted list [4, 9]. Start with lo = 0 and hi = 1. Both indices are still candidates. The midpoint rounds down to index zero, where the value is four.

Four is smaller than nine, so the answer must be to its right. If you write lo = mid, the next round starts with lo = 0 and hi = 1 again. Printing the bounds twice is enough to diagnose the loop. The target is present and the comparison is correct. The problem is that the comparison failed to remove a candidate.

Give each boundary a precise meaning

Use this rule for the version below: if the target exists and you have not returned it yet, its index lies between lo and hi, including both ends. Since you already checked the middle value, you can discard its index along with the half you ruled out.

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

Back on the two-number list, the first comparison moves lo to one. The second compares nine with nine and returns index one. If you search for seven instead, the second comparison moves hi to zero. The bounds cross, the loop exits, and the function returns -1.

Test the edges before the big list

assert binary_search([], 9) == -1
assert binary_search([9], 9) == 0
assert binary_search([4, 9], 9) == 1
assert binary_search([4, 9], 7) == -1

The empty list tests initialization. The single-item list catches a common mistake: changing the loop condition to lo < hi would skip the last candidate. The two-item tests prove that both a hit and a miss terminate.

This version expects ascending order and returns any matching index when values repeat. To find the first match, save a matching index and continue searching to its left. That is a different stopping rule. Try it on [4, 9, 9, 9] and decide which answer your caller needs.

Each failed comparison removes roughly half the remaining candidates. For a list with direct indexing, that gives logarithmic search time and constant extra space. NIST’s binary search reference

← All coding guides