Kodewick
Start learning →
Basic←→0 / 50

Binary search

#037Basiclo = mid + 18 min

The array is sorted small to big. Find which cell x is in (index from 0). Binary search looks at the middle cell a[mid]: if it is x, found; if smaller than x, look in the right half; if bigger, the left half. Write binary_search(a, n, x): return the index if found, -1 if not. Searching 7 in 1 3 5 7 9 11 returns 3.

Examples
binary_search({1, 3, 5, 7, 9, 11}, 6, 7)→3
binary_search({1, 3, 5, 7, 9, 11}, 6, 4)→-1
binary_search({2, 4, 6, 8}, 4, 2)→0
The functionint binary_search(int a[], int n, int x)
main.c
int binary_search(int a[], int n, int x) {
    int lo = 0, hi = n - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == x) {
            return mid;
        } else if (a[mid] < x) {
            // your code here: the middle is too small, search the right half
        } else {
            // your code here: the middle is too big, search the left half
        }
    }
    return -1;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.