Binary Search (C)
Topics: binary search, sorted array
Problem
Find a target in a sorted array in O(log n).
int binary_search(const int *nums, size_t n, int target); // index, or -1 if absent
Use a half-open range [lo, hi): mid = lo + (hi - lo) / 2 (avoids overflow); on a smaller
element move lo = mid + 1, otherwise hi = mid; the loop ends when lo == hi.
Run
cc -std=c11 -O2 -Wall tests.c -o /tmp/bs && /tmp/bs
Sign in to submit your solution.