← The C Language Lesson 70 of 77 · 10 XP

Searching

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Linear search means going through the items one by one. It works on any array, but in the worst case it looks at all n items.

Binary search works only on a sorted array, but it's incredibly fast: at every step it throws away half. A million items take no more than 20 steps.

int binary_search(const int *a, int n, int target)
{
    int lo = 0, hi = n - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;   // not (lo + hi) / 2 — that may overflow
        if (a[mid] == target)
            return mid;
        if (a[mid] < target)
            lo = mid + 1;               // what we're looking for is to the right
        else
            hi = mid - 1;               // what we're looking for is to the left
    }
    return -1;
}

Binary search is famous for how easy it is to write with an off-by-one error. Jon Bentley wrote that only about 10% of professional programmers got it right on the first try. Watch the <= and the ± 1 carefully.

The standard library has bsearch — it works with a comparison function, like qsort.

Task. Read an array sorted in ascending order (n, then n numbers) and several queries until the end of the input. For each query, print the index of the number or -1, using binary search.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.