low
Left boundary of the search interval. Moves right when the midpoint value is too small.
low = mid + 1
A library's digital catalog holds 200,000 titles sorted alphabetically. Rather than
scanning from A to Z, you open to the middle and discard half — repeating until the
answer emerges. Two pointers, low and high, define the
surviving interval; each comparison shrinks it by half. The answer arrives in
O(log n) comparisons.
The algorithm maintains a single invariant: the target, if present, is somewhere
between low and high inclusive. Every comparison
shrinks that window by half.
Left boundary of the search interval. Moves right when the midpoint value is too small.
low = mid + 1Right boundary of the search interval. Moves left when the midpoint value is too large.
high = mid − 1Computed each iteration as low + (high − low) / 2.
The value at mid is compared with the target.
The outer condition while (low ≤ high) ensures we stop once the
interval has collapsed — meaning the target is absent.
Calculate mid = low + (high − low) / 2. This formula avoids integer overflow.
Read nums[mid] and check if it equals, is less than, or is greater than the target.
If nums[mid] < target, the answer must be to the right → set low = mid + 1.
If nums[mid] > target, the answer must be to the left → set high = mid − 1.
If equal, we have found it.
Loop continues until low > high (target absent) or the target is found.
Binary search does not always find its target. Understanding the failure mode is as important as understanding the success path.
When low crosses past high, the search interval
is empty. No element in the array equals the target. The algorithm returns −1.
Try the "target absent" preset to watch the interval collapse.
When the array has just one element, low = high = 0 and
mid = 0. A single comparison resolves the answer immediately.
Try the "single element" preset.