The whole, before the parts

Binary search finds a value in an ordered collection by repeatedly ruling out half the remaining possibilities. Think of finding a name in an alphabetized directory: the ordering tells you which side to keep. Citation needed

Terminology and core concepts

Binary search locates a target in a sorted array by comparing it with the middle element. If the middle is too small, every element before it is too small too. The invariant (a fact preserved after every step) is that any occurrence still possible lies between low and high, inclusive. Each unsuccessful comparison removes the middle as well as one side. An empty interval means the target is absent. This version returns any matching index, not necessarily the first duplicate. Citation needed

Learning path

Trace an example

Find 31 in [4, 9, 15, 23, 31, 42, 58]
indices       low   mid   high   comparison
0..6           0     3     6     23 < 31: keep 4..6
4..6           4     5     6     42 > 31: keep 4..4
4..4           4     4     4     31 = 31: return 4
Three probes shrink seven candidates to one match; indices start at zero.

Implement it in Python

Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed

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

assert binary_search([4, 9, 15, 23, 31, 42, 58], 31) == 4
assert binary_search([], 31) == -1
assert binary_search([1, 3], 2) == -1

Citation needed

Analyze the cost

Each iteration at least halves the candidates: O(log n) worst-case time and O(1) extra space for random-access arrays. The best case is O(1). Sorting an unsorted input first adds its own cost. Citation needed

A mistake to watch for

Using low = mid instead of mid + 1 can leave the interval unchanged. Binary search is invalid on unsorted data. Citation needed

Practice and recall

  1. Trace a search for 10 in [2, 4, 6, 8]. What does it return?

    Work it out before opening the solution. Citation needed

    Show the reasoning
    1. Probe index 1: 4 is too small, so low becomes 2.
    2. Probe index 2: 6 is too small, so low becomes 3.
    3. Probe index 3: 8 is too small, so low becomes 4. The interval is empty; return -1.

    Citation needed

Why is it safe to discard the left half when the middle is too small?
Sorted order makes every element in that half too small. Citation needed

To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed

Sources