bsearch
Binary search of an array.
Defined in header <stdlib.h>
Syntax
#include <stdlib.h>
void *bsearch(const void *key, const void *base, size_t nelem, size_twidth,
int Cycmp) (const void *, const void *));
Portability
| DOS | UNIX | Windows | ANSI C | C++ only |
|---|---|---|---|---|
| ■ | ■ | ■ | ■ |
Remarks
bsearcti searches a table (array) of nelem elements in memory, and returns the address of the first entry in the table that matches the search key. The array must be in order. If no match is found, bsearch returns 0. Note that because this is a binary search, the first matching entry is not necessarily the first entry in the table.
The type sizej is defined as an unsigned integer.
D nelem gives the number of elements in the table. □ width specifies the number of bytes in each table entry.
The comparison routine *fcmp is called with two arguments: eleml and eleml. Each argument points to an item to be compared. The comparison function compares each of the pointed-to items i*eleml and *elem2), and returns an integer based on the results of the comparison.
For bsearch, the *fcmp return value is
< 0 if * eleml < * eleml == 0 if *eleml == *elem2 > 0 if * eleml > * eleml
Return value
bsearch returns the address of the first entry in the table that matches the search key. If no match is found, bsearch returns 0.
See also
Example
#include <stdlib.h>
#include <stdio.h>
typedef int (*fptr)(const void*, const void*);
#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))
int numarray[] = {123, 145, 512, 627, 800, 933};
int numeric (const int *pl, const int *p2)
{
return (*pl *p2)
ipragma argsused
int lookup (int key)
{
int *itemptr;
/* The cast of (int(*)(const void *,const void*)) is needed to avoid a type
mismatch error at compile time */
itemptr = (int *) bsearch (&key, numarray, NELEMS(numarray),
sizeof(int), (fptr)numeric);
return (itemptr != NULL);
}
int main(void)
{
if (lookup(512))
printf("512 is in the table.\n");
else
printf("512 isn't in the table.\n");
return 0;
Differences from modern implementations
Nothing recorded yet.
Modern references
These are search links, not yet checked by hand.
Stable link: /3.1/stdlib.h/bsearch/
· short form /3.1/bsearch/