Step by step · Python, C++ and Java

Binary search, visualized step by step

Binary search finds a value in a sorted array by checking the middle and throwing away the half that cannot contain it. Ten elements take at most four checks; a million take about twenty.

How it works
data = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
target = 23

lo = 0
hi = len(data) - 1
found = -1

while lo <= hi:
    mid = (lo + hi) // 2
    if data[mid] == target:
        found = mid
        break
    if data[mid] < target:
        lo = mid + 1
    else:
        hi = mid - 1

print(found)

How binary search works

Two indices, lo and hi, mark the part of the array that could still hold the target. Each iteration computes mid = (lo + hi) / 2 and compares data[mid] with the target. If it is too small, the target can only be to the right, so lo moves to mid + 1; if it is too large, hi moves to mid − 1. The loop ends when the value is found or lo passes hi.

The Python example searches [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] for 23.

What to watch for when it runs

  1. lo, mid and hi are drawn as pointers on the array, so the window visibly shrinks.
  2. Count the iterations: the window halves each time, so the loop runs only a handful of times.
  3. The condition lo <= hi and the ±1 updates are where most bugs live. Change one in the editor and run it again to see the loop stall or skip the answer.

Time and space complexity

Time
O(log n)
Space
O(1)

Each comparison halves the window, so n elements need at most ⌊log₂ n⌋ + 1 checks. The array must already be sorted.

Stuck on your own version?

Paste it into the visualizer and watch your own code run, line by line — bugs included.