Skip to content
Code it · Find the bug

Fix the binary search that never finishes

Searching for a value bigger than everything in the array never finishes.

Run it, watch what it really does on the array, and fix it. One small change is enough.

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