Looking for a name in a phone book, you never start at page one. You open the middle, see whether the name comes before or after, and throw away half the book. Binary search does exactly this on a sorted array: each comparison halves the part still to search, so even a million items need only about 20 comparisons. This lesson writes binary search iteratively and recursively, then extends it to lower and upper bounds and to “searching on the answer”.
In this lesson you will learn
- Iterative and recursive binary search
- Why the array must be sorted
- Calculating the middle index without overflow
- Lower bound and upper bound for duplicates and insertion points
- Binary search on the answer, such as an integer square root
You should know arrays and recursion. Sorted data can come from a sorting algorithm or qsort.
Classic Binary Search
#include <stdio.h>
/* Iterative binary search: returns the index of key in sorted a[0..n-1], or -1 */
static int binary_search(const int *a, int n, int key, int *steps) {
int lo = 0, hi = n - 1;
*steps = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; /* avoids overflow of lo + hi */
(*steps)++;
if (a[mid] == key) return mid;
if (a[mid] < key) lo = mid + 1; /* key is in the right half */
else hi = mid - 1; /* key is in the left half */
}
return -1;
}
/* Recursive version of the same idea */
static int bsearch_rec(const int *a, int lo, int hi, int key) {
if (lo > hi) return -1;
int mid = lo + (hi - lo) / 2;
if (a[mid] == key) return mid;
return a[mid] < key ? bsearch_rec(a, mid + 1, hi, key) : bsearch_rec(a, lo, mid - 1, key);
}
int main(void) {
int roll[] = {3, 8, 15, 21, 27, 34, 42, 56, 63, 71, 88, 95};
int n = sizeof roll / sizeof roll[0];
int keys[] = {42, 3, 95, 50};
for (int i = 0; i < 4; i++) {
int steps;
int idx = binary_search(roll, n, keys[i], &steps);
printf("key %2d -> index %2d after %d steps (recursive: %d)\n",
keys[i], idx, steps, bsearch_rec(roll, 0, n - 1, keys[i]));
}
/* Worst-case steps grow very slowly: about log2(n) + 1 */
static int big[1000000];
for (int i = 0; i < 1000000; i++) big[i] = 2 * i;
int steps;
binary_search(big, 1000000, 1, &steps); /* odd key: not present */
printf("1,000,000 items: %d steps to prove 1 is missing\n", steps);
return 0;
}
Output
key 42 -> index 6 after 3 steps (recursive: 6)
key 3 -> index 0 after 3 steps (recursive: 0)
key 95 -> index 11 after 4 steps (recursive: 11)
key 50 -> index -1 after 4 steps (recursive: -1)
1,000,000 items: 20 steps to prove 1 is missing
loandhimark the part of the array that could still contain the key. Each step compares the key with the middle element and discards the half that cannot contain it.lo + (hi - lo) / 2gives the middle without the overflow that(lo + hi) / 2can cause when the indexes are very large.- When
lopasseshi, the range is empty and the key is not present, so the function returns -1. The key 50 needed 4 steps to prove it is missing. - The recursive version follows the same logic, calling itself on one half. The loop version is usually preferred because it uses no extra stack space.
- For a million sorted items, a missing key took only 20 steps. A linear search would check all 1,000,000.
- Binary search only works on sorted data. On an unsorted array it can miss keys that are present.
Bounds and Searching on the Answer
#include <stdio.h>
/* First index i with a[i] >= key (lower bound); returns n if none */
static int lower_bound(const int *a, int n, int key) {
int lo = 0, hi = n; /* search in [lo, hi) */
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] < key) lo = mid + 1;
else hi = mid;
}
return lo;
}
/* First index i with a[i] > key (upper bound) */
static int upper_bound(const int *a, int n, int key) {
int lo = 0, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] <= key) lo = mid + 1;
else hi = mid;
}
return lo;
}
/* Binary search on the answer: integer square root */
static int isqrt(int x) {
int lo = 0, hi = x < 2 ? x : x / 2, ans = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if ((long long)mid * mid <= x) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
int main(void) {
int marks[] = {40, 55, 55, 55, 60, 72, 72, 90};
int n = sizeof marks / sizeof marks[0];
int first = lower_bound(marks, n, 55), last = upper_bound(marks, n, 55);
printf("55 appears at indexes %d..%d, count %d\n", first, last - 1, last - first);
printf("72 count: %d, 50 count: %d\n",
upper_bound(marks, n, 72) - lower_bound(marks, n, 72),
upper_bound(marks, n, 50) - lower_bound(marks, n, 50));
printf("insert 65 at index %d to keep the array sorted\n", lower_bound(marks, n, 65));
printf("students with 60 or more: %d\n", n - lower_bound(marks, n, 60));
int xs[] = {0, 1, 15, 16, 1000000};
for (int i = 0; i < 5; i++) printf("isqrt(%d) = %d\n", xs[i], isqrt(xs[i]));
return 0;
}
Output
55 appears at indexes 1..3, count 3
72 count: 2, 50 count: 0
insert 65 at index 5 to keep the array sorted
students with 60 or more: 4
isqrt(0) = 0
isqrt(1) = 1
isqrt(15) = 3
isqrt(16) = 4
isqrt(1000000) = 1000
lower_boundreturns the first index whose value is at least the key, andupper_boundthe first index whose value is greater than the key. Both search the half-open range[lo, hi).- Their difference counts how many times a value appears: 55 appears three times, at indexes 1 to 3. A value that is absent, such as 50, gives 0.
lower_boundis also the position where a new value can be inserted while keeping the array sorted, andn - lower_bound(60)counts values of 60 or more.isqrtdoes not search an array at all. It searches the range of possible answers, checking whethermid * mid <= x. This “binary search on the answer” works whenever a yes/no test switches from yes to no only once.- The product is computed as
long longso that large values ofmidcannot overflow anint.
Linear vs Binary Search
| Items | Linear search (worst case) | Binary search (worst case) |
|---|---|---|
| 10 | 10 comparisons | 4 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
| 1,000,000,000 | 1,000,000,000 | 30 |
Binary search is O(log n). The price is that the data must be sorted first, which costs O(n log n), so it pays off when you search the same data many times. The standard library offers bsearch for this.
Common Mistakes
- Searching unsorted data.
- Infinite loops from updating
lo = midinstead oflo = mid + 1in the classic version. - Mixing range conventions: using
hi = n - 1with alo < hiloop, orhi = nwithlo <= hi. Choose closed[lo, hi]or half-open[lo, hi)and stay consistent. - Overflow in
(lo + hi) / 2on very large ranges.
Practice Exercises
Exercise 1. Using lower_bound, check whether 72 is present in marks.
Show answer
int i = lower_bound(marks, n, 72);
int present = (i < n && marks[i] == 72); /* 1: found at index 5 */
Exercise 2. How many steps does binary search need, at most, for 5,000 items?
Show answer
13. Each step halves the range, and 212 = 4,096 is less than 5,000 while 213 = 8,192 is more, so the range shrinks to nothing within 13 comparisons.
Frequently Asked Questions
Can binary search work on a linked list?
Not efficiently. Reaching the middle of a linked list takes O(n) steps, so the advantage disappears. Binary search needs random access, as arrays provide.
Which index does binary search return when the key appears several times?
The classic version returns whichever matching index it lands on first, which is not guaranteed to be the first or last. Use lower_bound or upper_bound when you need a specific one.
Summary
- Binary search halves the search range each step: O(log n).
- The data must be sorted.
- Compute the middle as
lo + (hi - lo) / 2. - Lower and upper bounds count duplicates and find insertion points.
Next: The sizeof Operator in C.
