data-structures · intermediate · ~15 min

Binary search

Halve the search space each step.

Challenge

Implement int binary_search(const int *a, int n, int target) on a sorted (ascending) array, returning an index of target or -1 if absent.

Starter code

int binary_search(const int *a, int n, int target) {
    /* TODO */
    return -1;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.