Binary search
Every comparison throws away half the array. That is the whole algorithm.
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 possible8 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.
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.
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;}