data-structures · intermediate · ~20 min
Recursion with monotonic shrink and the classic mid-point overflow trap.
Search a sorted array for a value using recursion.
Implement int bsearch_rec(const int *a, int lo, int hi, int target) that returns an index of target in the sorted array a, searching the half-open range [lo, hi), or -1 if target is not present in that range.
a: an int array sorted in non-decreasing order (read-only).lo: inclusive lower bound of the search range.hi: exclusive upper bound of the search range.target: the value to find.int: an index i in [lo, hi) with a[i] == target, or -1 if absent. If several elements equal target, any matching index is acceptable.
a = {1, 3, 5, 7, 9}
bsearch_rec(a, 0, 5, 5) -> 2
bsearch_rec(a, 0, 5, 1) -> 0
bsearch_rec(a, 0, 5, 9) -> 4
bsearch_rec(a, 0, 5, 10) -> -1
lo == hi) returns -1.lo + (hi - lo) / 2, not (lo + hi) / 2, to avoid integer overflow on large indices.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 a; half-open range [lo, hi); target.
int: an index of target, or -1 if absent.
Recursive only. O(log n). Use lo + (hi-lo)/2 for the midpoint.
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.