Skip to content
Codescope

Binary search

Every comparison throws away half the array. That is the whole algorithm.

core9 min8 steps

Before you start

You're guessing a number between 1 and 100. Every guess, you get told "higher" or "lower". What's the fewest guesses needed to be sure? Seven — because each guess halves the remaining range.

**Binary search** is exactly that algorithm applied to a sorted array. Look at the middle. Too big? Discard the right half. Too small? Discard the left half. Repeat. A million-element array takes about 20 comparisons.

But binary search is famously easy to get *slightly* wrong. This lesson steps through the algorithm, points at the classic off-by-one and integer-overflow traps, and shows you the version that actually works.

Sorted array

8 of 8 elements still possible
arrtarget = 41
[0]
3
lo
[1]
8
[2]
12
[3]
19
[4]
27
[5]
34
[6]
41
[7]
56
hi

8 elements. A linear scan needs up to 8 comparisons; this will need 3.

Step 1 of 8. The array must already be sorted. Binary search needs one guarantee: if `arr[mid]` is smaller than the target, everything to its left is smaller too. That is the entire reason it works, and the entire reason it fails silently on unsorted input — it will not error, it will just return `-1` for a value that is present.

01 / 08

Step 01 / 08

The array must already be sorted

Binary search needs one guarantee: if arr[mid] is smaller than the target, everything to its left is smaller too.

That is the entire reason it works, and the entire reason it fails silently on unsorted input — it will not error, it will just return -1 for a value that is present.

binary-search.cC
int binary_search(int arr[], int n, int target) {    int lo = 0;    int hi = n - 1;    while (lo <= hi) {        int mid = lo + (hi - lo) / 2;        if (arr[mid] == target)            return mid;        else if (arr[mid] < target)            lo = mid + 1;        else            hi = mid - 1;    }    return -1;}