Name
bsearch
Synopsis
Searches an array for a specified key
#include <stdlib.h> void *bsearch( const void *key, const void *array, size_tn, size_tsize, 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access