algorithms · high
Binary Search
Binary search locates a target in a sorted array by checking the middle element and discarding the half that cannot contain the target, halving the search space each step for O(log n) time. The classic bugs are off-by-one loop bounds and computing the midpoint as (lo+hi)/2, which can overflow — use lo + (hi-lo)/2.
Binary search halves a SORTED array's search window each step by comparing the middle element to the target; O(log n) time. Compute mid as lo + (hi-lo)/2 to avoid overflow.
The code
int binarySearch(int a[], int n, int target) { int lo = 0, hi = n - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; // avoids (lo+hi) overflow if (a[mid] == target) return mid; // found it else if (a[mid] < target) lo = mid + 1; // search the right half else hi = mid - 1; // search the left half } return -1; // not present}What this lesson walks through
- 01Binary search — needs a SORTED array
- 02a[3] = 4 < 7 — go right
- 03a[5] == 7 — found
Binary search finds a target in a sorted array by repeatedly halving the search window: check the middle, then keep only the half that could contain the target. Here we search for 7.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Binary Search and 100+ animated C++ interview lessons.