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
- lo, mid and hi are drawn as pointers on the array, so the window visibly shrinks.
- Count the iterations: the window halves each time, so the loop runs only a handful of times.
- 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.