You have a sorted list of 1,024 numbers. Do you need to look at all of them to find one? With binary search, at most 11 checks of the middle element settle the question.

Follow the part where the answer can still be

Look for 7 in the sorted list [1, 3, 5, 7, 9]. Indices start at zero.

Candidate indices Middle index Value Decision
0–4 2 5 7 is larger, so keep 3–4
3–4 3 7 Return index 3

After looking at 5, you can discard it and everything to its left. Sorted order is what makes that decision valid. The rule to remember is that if the target exists, it must still be between the two bounds, inclusive.

Write the loop in Python

def binary_search(values: list[int], target: int) -> int: low = 0 high = len(values) - 1 while low <= high: mid = low + (high - low) // 2 value = values[mid] if value == target: return mid if value < target: low = mid + 1 else: high = mid - 1 return -1 

The loop uses low <= high because a range with one remaining index still needs a check. Both updates exclude mid: it was already checked. If the bounds cross, the list contains no matching value.

Check the boundaries

assert binary_search([], 7) == -1 assert binary_search([7], 7) == 0 assert binary_search([1, 3, 5, 7, 9], 1) == 0 assert binary_search([1, 3, 5, 7, 9], 9) == 4 assert binary_search([1, 3, 5, 7, 9], 6) == -1 assert binary_search([1, 3, 3, 3, 5], 3) in (1, 2, 3) 

The duplicate case can return any matching index. If you need the first one in Python, use bisect_left and check that the returned index is in bounds and holds the target.

Each iteration leaves at most half the candidate indices. For a nonempty list, the worst case takes ⌊log₂(n)⌋ + 1 midpoint checks, so time is O(log n). The iterative loop uses O(1) auxiliary space. Those bounds assume the list is already sorted and indexing takes constant time.

Try tracing a search for 6 by hand. When the bounds cross, you’ll see how the same rule explains both a match and a miss.