📊Go deeper — read the bookSorting algorithms, end to end— runnable code & full walkthrough →

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.

🔑 Key line

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

  1. 01Binary search — needs a SORTED array
  2. 02a[3] = 4 < 7 — go right
  3. 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.

← Previous
Quick Sort
Next →
Matrix Multiplication