data-structures · intermediate · ~15 min
Halve the search space each step.
Find a value in a sorted array by repeatedly halving the search range.
Implement int binary_search(const int *a, int n, int target) on a sorted (ascending) array. Return an index where target is found, or -1 if it is absent.
a: array of n ints sorted in ascending order (read-only).n: the number of elements.target: the value to search for.int: an index i with a[i] == target, or -1 if target is not present.
a={1,3,5,7,9,11}, target=7 -> 3
a={1,3,5,7,9,11}, target=1 -> 0
a={1,3,5,7,9,11}, target=8 -> -1 (absent)
a: n ints sorted ascending; n; target.
int: an index of target, or -1 if absent.
Input is sorted ascending; halve the range each step.
int binary_search(const int *a, int n, int target) {
/* TODO */
return -1;
}
Off-by-one in low/high boundary updates; integer overflow in (low + high) / 2 instead of low + (high - low) / 2; infinite loop when bounds don't progress.
Empty array; target element not present; target at index 0 or index len-1; array with all identical elements.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.