data-structures · intermediate · ~15 min

Binary search

Search in O(log n) with strict bounds.

Challenge

Implement long binary_search(const int *a, size_t n, int target) returning the index of target in the sorted array a, or -1 if not present. If there are duplicates, any matching index is acceptable.

Starter code

#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.