Name

bsearch

Synopsis

Searches an array for a specified key

#include <stdlib.h>
void *bsearch( const void *key, const void *array, size_t n, size_t size,
               int (*compare)(const void *, const void *));

The bsearch() function uses the binary search algorithm to find an element that matches key in a sorted array of n elements of size size. (The type size_t is defined in stdlib.h as unsigned int.) The last argument, compare, gives bsearch() a pointer to a function that it calls to compare the search key with any array element. This function must return a value that indicates whether its first argument, the search key, is less than, equal to, or greater than its second argument, an array element to test. For a detailed description of such comparison functions, see qsort() in this chapter.

You should generally use qsort() before bsearch(), because the array must be sorted before searching. This step is necessary because the binary search algorithm tests whether the search key is higher or lower than the middle element in the array, then eliminates half of the array, tests the middle of the result, eliminates half again, and so forth. If you define the comparison function for bsearch() with identical types for its two arguments, then qsort() can use the same comparison function.

The bsearch() function returns a pointer to the first array element found that matches the search key. If no matching element is found, bsearch() returns a null pointer.

Example

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

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.