Skip to content
Devtoolry

Arrays and algorithms · intermediate

C Program for Binary Search

Implement binary search in C on a sorted array with low, high and mid indexes, avoid the classic (low + high) / 2 overflow, and use bsearch() from stdlib.h.

Binary search checks the middle element of a sorted array and discards the half that cannot contain the target. Each step halves the range, so even a million elements need at most 20 comparisons.

The program

C
#include <stdio.h>

int binary_search(const int *a, int n, int target) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (a[mid] == target)
            return mid;
        if (a[mid] < target)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return -1;
}

int main(void) {
    int numbers[] = {3, 8, 15, 23, 42, 57, 71, 89};
    int n = sizeof numbers / sizeof numbers[0];
    printf("42 is at index %d\n", binary_search(numbers, n, 42));
    printf("10 is at index %d\n", binary_search(numbers, n, 10));
    return 0;
}
Output
42 is at index 4
10 is at index -1

How it works

  1. low and high are the first and last indexes that could still hold the target.
  2. mid = low + (high - low) / 2 is the middle; written this way it cannot overflow, unlike (low + high) / 2.
  3. If the middle value is too small the target can only be to the right (low = mid + 1), otherwise to the left (high = mid - 1).
  4. When low passes high the range is empty and the function returns -1.

Another way: bsearch() from stdlib.h

bsearch() takes the same kind of comparison function as qsort() and returns a pointer to the found element, or NULL. Subtracting the array's start gives the index.

C
#include <stdio.h>
#include <stdlib.h>

int compare_ints(const void *p, const void *q) {
    int x = *(const int *)p, y = *(const int *)q;
    return (x > y) - (x < y);
}

int main(void) {
    int numbers[] = {3, 8, 15, 23, 42, 57, 71, 89};
    int key = 57;
    int *found = bsearch(&key, numbers, 8, sizeof numbers[0], compare_ints);
    if (found)
        printf("%d found at index %td\n", key, found - numbers);
    return 0;
}
Output
57 found at index 5

Common mistakes

  • Searching an unsorted array, which gives wrong answers without any warning.
  • Writing while (low < high), which misses the target when it is the last remaining element.
  • Updating low = mid instead of mid + 1, which can loop forever.

Try it yourself

  • Write a recursive version that takes low and high as parameters.
  • Return the first index of a value that appears several times.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.