bsearch

Description

Performs a binary search of a sorted array.

#include <stdlib.h> Required for ANSI compatibility  
#include <search.h> Required only for function declarations  

void *bsearch( const void *key, const void *base, size_t num, size_t width,
int ( __cdecl *compare )( const void *elem1, const void *elem2 ) );

key Object to search for  
base Pointer to base of search data  
num Number of elements  
width Width of elements  
compare Function that compares two elements: elem1 and elem2  
elem1 Pointer to the key for the search  
elem2 Pointer to the array element to be compared with the key  

Remarks

The bsearch function performs a binary search of a sorted array of num elements, each of width bytes in size. The base value is a pointer to the base of the array to be searched, and key is the value being sought.

The compare argument is a pointer to a user-supplied routine that compares two array elements and returns a value specifying their relationship. The bsearch function calls the compare routine one or more times during the search, passing pointers to two array elements on each call. The routine compares the elements, then returns one of the following values:

Value Meaning

< 0 elem1 less than elem2
= 0 elem1 identical to elem2
> 0 elem1 greater than elem2

If the array you are searching is not in ascending sort order, bsearch does not work properly. If the array contains duplicate records with identical keys, there is no way to predict which of the duplicate records will be located by bsearch.

Return Value

The bsearch function returns a pointer to an occurrence of key in the array pointed to by base. If key is not found, the function returns NULL.

Compatibility

Standards:ANSI, UNIX

16-Bit:DOS, QWIN, WIN, WIN DLL

32-Bit:DOS32X

See Also

_lfind, _lsearch, qsort

Example

/* BSEARCH.C: This program reads the command-line arguments, sorting them

* with qsort, and then uses bsearch to find the word "cat."

*/

#include <search.h>

#include <string.h>

#include <stdio.h>

int compare( char **arg1, char **arg2 ); /* Declare a function for compare */

void main( int argc, char **argv )

{

char **result;

char *key = "cat";

int i;

/* Sort using Quicksort algorithm: */

qsort( (char *)argv, argc, sizeof( char * ), compare );

for( i = 0; i < argc; ++i ) /* Output sorted list */

printf( "%s ", argv[i] );

/* Find the word "cat" using a binary search algorithm: */

result = (char **)bsearch( (char *) &key, (char *)argv, argc,

sizeof( char * ), compare );

if( result )

printf( "\n%s found at %Fp\n", *result, result );

else

printf( "\nCat not found!\n" );

}

int compare( char **arg1, char **arg2 )

{

/* Compare all of both strings: */

return _strcmpi( *arg1, *arg2 );

}

Output

[C:\LIBREF] bsearch dog pig horse cat human rat cow goat

bsearch cat cow dog goat horse human pig rat

cat found at 0292:0FD0