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.
a is sorted array of ints; lo and hi define half-open search range [lo, hi).
int bsearch_rec(const int *a, int lo, int hi, int target) { /* TODO */ return -1; }
Integer overflow in (lo + hi) / 2 or infinite recursion on boundary updates.
lo >= hi (empty range), target at a[lo], target at a[hi-1], target not in array.
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.