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.
n items you need about log₂(n) comparisons — much fewer than linear search for large n.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
Run the simulation
Grey cells are discarded. Blue / green / orange markers show lo, mid, and hi.
Binary search essentials
Three pointers, one invariant: the target can only live between lo and hi.
Must be sorted first
If the array is unsorted, discarding a half is wrong — you’d skip the target.
Logarithmic time
Each step halves the remaining range, so the search shrinks very quickly.
Keep lo ≤ hi
When lo passes hi, the range is empty and the target is not present.