Binary search in C, visualized step by step
To find a value in a sorted array, look at the middle one: if it is smaller than the target, search the right half; if bigger, the left half. Every look rules out half of what is left.
binary_search.c
#include <stdio.h>
int main(void) {
int a[] = {2, 5, 8, 12, 16, 23, 38, 56, 72};
int n = 9, target = 23;
int lo = 0, hi = n - 1, found = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) {
found = mid;
break;
} else if (a[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
printf("%d\n", found);
return 0;
}
How Binary search works
- lo and hi mark the two ends of the range that may still hold the answer.
- Look at the middle, mid: if it is the target, done.
- mid smaller than the target: the answer is to the right, lo = mid + 1; bigger: hi = mid − 1.
- When lo passes hi, the value is not there.
What to watch
lo and hiThe distance between them roughly halves every step.
midWith 9 values it takes at most 4 looks to know the answer.
FAQ
What is the time complexity of binary search?
O(log n): each step halves the range, so a million values take at most 20 looks.
What does binary search need?
A sorted array that can be indexed directly (a linked list will not do).
Why write mid as lo + (hi − lo) / 2?
In C, lo + hi can overflow an int; this form cannot. Python integers have no limit, so (lo + hi) // 2 is fine there.