data-structures · intermediate · ~15 min
Search a sorted array by halving the range.
Implement:
int binary_search(const int *a, int n, int target);
Recursively search the sorted (ascending, distinct) array for target. Return an index where it occurs, or -1.
Sorted a, length n, target.
An index of target, or -1.
Recurse on the correct half.
#include <stddef.h>
/* Recursive binary search in a sorted (ascending, distinct) array. Return an index of target, or -1. */
int binary_search(const int *a,int n,int target){ (void)a;(void)n;(void)target; return -1; }
Integer overflow in (lo+hi)/2; recursing on the wrong half.
Empty range returns -1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.