Binary Search
Binary search finds a target in a sorted array by repeatedly discarding half of the remaining range. It runs in O(log n) comparisons and needs random access.
Detailed Explanation
The array must be sorted under the same order you compare with. You keep a half-open range [lo, hi). The midpoint is lo + (hi - lo) / 2, not (lo + hi) / 2, so the addition cannot overflow a large size_t. You compare a[mid] to the key. Equal: done. Key greater: the answer, if any, is in [mid + 1, hi). Key smaller: [lo, mid). Each step shrinks the range. When lo == hi, the key is absent; lo is the insertion point.
Off-by-one errors are the entire sport. Inclusive hi wants while (lo <= hi) and hi = mid - 1, and mid - 1 underflows if mid is 0 and the index is unsigned. Half-open ranges avoid that: hi is never decremented below lo past zero in a way that wraps, because you set hi = mid.
Binary search is not only "is this value present." Lower bound (first index with a[i] >= key) and upper bound (first index with a[i] > key) are the forms that make range counts and insertions easy. bsearch only answers presence. Writing the loop yourself is justified the moment you need an index.
The model assumes O(1) indexing. On a linked list, "the middle" is an O(n) walk and the algorithm becomes linear. On a BST, the same idea is a tree walk and you already have the structure.
A predicate version — "find the first index where ok(i) is true, given that ok flips from false to true once" — is the same loop with a[mid] replaced by a test. That is how you binary-search a monotonic function, an answer space, or a file of sorted records.
Code Examples
#include <stdio.h>
#include <stddef.h>
/* Returns the index, or n if not found. Range is [lo, hi). */
static size_t bfind(const int *a, size_t n, int key)
{
size_t lo = 0, hi = n;
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
if (a[mid] == key) {
return mid;
}
if (a[mid] < key) {
lo = mid + 1;
} else {
hi = mid;
}
}
return n;
}
int main(void)
{
int a[] = { 1, 3, 5, 7, 9 };
printf("%zu %zu\n", bfind(a, 5, 7), bfind(a, 5, 8));
/* prints: 3 5 */
return 0;
}#include <stdio.h>
#include <stddef.h>
/* First index with a[i] >= key (lower bound). */
static size_t lower_bound(const int *a, size_t n, int key)
{
size_t lo = 0, hi = n;
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
if (a[mid] < key) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
int main(void)
{
int a[] = { 1, 3, 3, 7 };
printf("%zu\n", lower_bound(a, 4, 3)); /* prints: 1 */
return 0;
}Common Gotchas
`(lo + hi) / 2` overflows when `lo` and `hi` are large `size_t` values
write `lo + (hi - lo) / 2`.
`hi = mid - 1` with unsigned `mid == 0` wraps to `SIZE_MAX`
use a half-open range and `hi = mid`.
The array must be sorted in the same order as the compare
an unsorted input is not "degraded performance," it is a wrong answer.
`bsearch` will not give you the insertion index
keep your own loop when you need it.