Binary search keeps a range [lo, hi] of the sorted array that could contain the key. It compares the key with the middle element: if equal it is done; if the key is larger it continues in the upper half; if smaller, the lower half. The range halves every step, so at most about log2(n) + 1 comparisons are needed. The array must be sorted.
Remember
mid = lo + (hi - lo) / 2;
if (a[mid] == key) found;
else if (a[mid] < key) lo = mid + 1;
else hi = mid - 1;
Reference
Cheat Sheet
Keep these facts handy while you work with Binary Search in C.
#include <stdio.h>
int main(void) {
int a[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int lo = 0, hi = 9, key = 23;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == key) {
printf("mid=%d value=%d -> found\n", mid, a[mid]);
printf("index: %d\n", mid);
return 0;
}
if (a[mid] < key) {
printf("mid=%d value=%d -> go right\n", mid, a[mid]);
lo = mid + 1;
} else {
printf("mid=%d value=%d -> go left\n", mid, a[mid]);
hi = mid - 1;
}
}
printf("not found\n");
return 0;
}
Output
mid=4 value=16 -> go right
mid=7 value=56 -> go left
mid=5 value=23 -> found
index: 5
How It Works
The first midpoint is index 4 (16), which is less than 23, so the range becomes indexes 5 to 9.
The midpoint of 5 to 9 is index 7 (56), which is greater, so the range becomes 5 to 6.
The midpoint of 5 to 6 is index 5, which holds 23.
Edge Cases & Pitfalls
Check these before relying on Binary Search in real programs.
unsorted
Unsorted input
The halving logic is only valid when the array is sorted.
loop
Off-by-one updates
Use mid + 1 and mid - 1; using mid can loop forever.
Remember
Key Takeaways
Halve the range each step.
Sorted data only.
O(log n).
One line: Binary search keeps a range [lo, hi] of the sorted array that could contain the key.
Frequently Asked Questions
It compares the key with the middle element of a sorted range and discards the half that cannot contain the key, repeating until found or the range is empty.
At most about log2(n) + 1 comparisons.
Continue with "Iterative Binary Search in C" next. A reusable loop-based binary search plus a first-occurrence variant. The C Searching Algorithms hub lists every topic in order.