Binary search

When the array is sorted, each comparison can throw away half of what remains. Follow lo, mid, and hi as they close in.

Algorithms Beginner+ Arrays · Search ~6 min
The idea

Halve the problem each step

Pick the middle element. If it’s too small, the target (if present) must be on the right — discard the left half. If it’s too big, discard the right half.

Repeat until you find the target or the range is empty. That’s why binary search needs a sorted array.

TipWith n items you need about log₂(n) comparisons — much fewer than linear search for large n.
IdeaCore loop
binary_search.pyPython
while lo <= hi:
    mid = (lo + hi) // 2
    if arr[mid] == target: return mid
    if arr[mid] < target: lo = mid + 1
    else: hi = mid - 1

Sorted array: [2, 5, 8, 13, 21, 34] · Target: 13

Interactive

Run the simulation

Grey cells are discarded. Blue / green / orange markers show lo, mid, and hi.

Step 0 / 0
demo.pyPython
Array + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember

Binary search essentials

Three pointers, one invariant: the target can only live between lo and hi.

Sorted

Must be sorted first

If the array is unsorted, discarding a half is wrong — you’d skip the target.

O(log n)

Logarithmic time

Each step halves the remaining range, so the search shrinks very quickly.

Invariant

Keep lo ≤ hi

When lo passes hi, the range is empty and the target is not present.