Syntax
#include <stdlib.h> /* also in <search.h> */ void *bsearch(const void *key, const void *base, size_t num, size_t size, int (*compare)(const void *key, const void *element));Description
bsearch performs a binary search of an array of num elements, each of size bytes. The array must be sorted in ascending order by the function pointed to by compare. The base is a pointer to the base of the array to search, and key is the value being sought.
The compare argument is a pointer to a function you must supply that takes a pointer to the key argument and to an array element, in that order. bsearch calls this function one or more times during the search. The function must compare the key and the element and return one of the following values: compact break=fit.
Value
bsearch returns a pointer to key in the array to which base points. If two keys are equal, the element that key will point to is unspecified. If bsearch cannot find the key, it returns NULL.
This example performs a binary search on the argv array of pointers to the program parameters and finds the position of the argument PATH. It first removes the program name from argv, and then sorts the array alphabetically before calling bsearch. The functions compare1 and compare2 compare the values pointed to by arg1 and arg2 and return the result to bsearch.
#include <stdlib.h>#include <stdio.h> #include <string.h> int compare1(const void *arg1,const void *arg2) { return (strcmp(*(char **)arg1, *(char **)arg2)); } int compare2(const void *arg1,const void *arg2) { return (strcmp((char *)arg1, *(char **)arg2)); } int main(int argc,char *argv[]) { char **result; char *key = "PATH"; int i; argv++; argc--; qsort((char *)argv, argc, sizeof(char *), compare1); result = (char **)bsearch(key, argv, argc, sizeof(char *), compare2); if (result != NULL) { printf("result = <%s>\n", *result); } else printf("result is null\n"); return 0; /**************************************************************************** If the program name is progname and you enter: progname where is PATH in this phrase? The output should be: result = <PATH> ****************************************************************************/ }Related Information