data-structures · intermediate · ~20 min
Recursion with monotonic shrink and the classic mid-point overflow trap.
Implement int bsearch_rec(const int *a, int lo, int hi, int target) that returns the index of target in the sorted array a over the half-open range [lo, hi), or -1 if the value is not present.
a is sorted in non-decreasing order.lo and hi are inclusive/exclusive respectively.target, any valid index is acceptable.a = {1, 3, 5, 7, 9}
bsearch_rec(a, 0, 5, 5) -> 2
bsearch_rec(a, 0, 5, 10) -> -1
bsearch_rec(a, 0, 5, 1) -> 0
bsearch_rec(a, 0, 5, 9) -> 4
lo + (hi - lo) / 2 instead of (lo + hi) / 2 to avoid integer overflow on large indices.lo == hi) → return -1.Binary search is the canonical divide-and-conquer algorithm. The recursive form is shorter; the iterative form is fractionally faster (no stack frames). Implementing both is a rite of passage for every C developer.
Sorted int array, half-open range [lo, hi), target value.
Index of target or -1.
Recursive only. O(log n).
int bsearch_rec(const int *a, int lo, int hi, int target) { /* TODO */ return -1; }
Using (lo + hi) / 2 — overflow when lo + hi > INT_MAX. Going off-by-one on the range (mixing inclusive and exclusive bounds).
Empty range; single element; target absent; duplicates.
O(log n) time, O(log n) stack space.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.