data-structures · intermediate · ~15 min
Search in O(log n) with strict bounds.
Find a target in a sorted array in O(log n) by repeatedly halving the search range.
Implement long binary_search(const int *a, size_t n, int target) returning the index of target in the ascending-sorted array a, or -1 if it is not present. No main — the grader calls it.
a: an array of int sorted in ascending order.n: the number of elements (may be 0).target: the value to locate.The index of target as a long, or -1 if absent. If duplicates exist, any matching index is acceptable.
binary_search({1,3,5,7,9,11,13}, 7, 1) -> 0
binary_search({1,3,5,7,9,11,13}, 7, 13) -> 6
binary_search({1,3,5,7,9,11,13}, 7, 6) -> -1
binary_search(a, 0, 5) -> -1
n = 0) returns -1.-1.mid as lo + (hi - lo)/2 to avoid overflow. The array is assumed sorted.A sorted int array a, its length n, and the target value.
The index of target as a long, or -1 if not present.
Array is sorted ascending; run in O(log n).
#include <stddef.h>
long binary_search(const int *a, size_t n, int target) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.