Course contentsShow
← C
Lesson 880 of 1,21912. The Standard LibraryFree lesson

Using `bsearch` on sorted arrays

Using bsearch on sorted arrays

What you'll learn: How to efficiently find a specific element in a sorted array using the standard library's binary search function.

The Library's Bloodhound

Searching for a needle in a haystack is easy if the hay is organized by size. Instead of checking every single straw from left to right (a linear search), you can jump to the middle, see if your needle is bigger or smaller than that straw, and throw away half the pile. In C, the bsearch function performs this "binary search" for you.

To use it, your array must already be sorted. Like its sibling qsort, bsearch is generic, meaning it doesn't know if it is searching for integers, strings, or custom structs. You have to tell it how to compare items.

How to call bsearch

The function requires five arguments:

  1. Key: A pointer to the value you are looking for.
  2. Base: The array to search.
  3. Num: The number of elements in the array.
  4. Size: The size of each element in bytes.
  5. Comparator: A function that returns an integer (negative, zero, or positive) to guide the search.

If the item is found, bsearch returns a pointer to it. If not, it returns NULL.

Code Example: Finding an ID

Imagine you have a sorted list of employee IDs and you want to verify if a specific ID exists.

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

// The comparator: returns 0 if they match
int compare_ints(const void *a, const void *b) {
    int arg1 = *(const int *)a;
    int arg2 = *(const int *)b;
    return (arg1 > arg2) - (arg1 < arg2);
}

int main() {
    int ids[] = {102, 205, 308, 412, 550}; // Must be sorted!
    int key = 412; // The ID we are looking for
    int num_ids = 5;

    int *item = bsearch(&key, ids, num_ids, sizeof(int), compare_ints);

    if (item != NULL) {
        printf("Found ID %d at address %p\n", *item, (void*)item);
    } else {
        printf("ID %d not found.\n", key);
    }

    return 0;
}

Why use it?

For an array of 1,000 items, a linear search might take 1,000 steps. Binary search takes about 10. By providing a pointer to the key and a comparison rule, bsearch handles the logic of jumping through the memory, making your search lightning-fast without you having to write the complex "divide and conquer" logic yourself.

Key takeaway

Use bsearch for high-performance searching on sorted data, but always remember it returns a pointer to the found element (or NULL), not the index.