Everything

bsearch


Binary search

[Classification]

Standard library

[Syntax]

#include <stdlib.h>

void* bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *,

const void*));

[Return value]

A pointer to the element in the array that coincides with key is returned. If there are two or more elements that coincide with key, the one that has been found first is indicated. If there are not elements that coincide with key, a null pointer is returned.

[Description]

This function searches an element that coincides with key from an array starting with base by means of binary search. nmemb is the number of elements of the array. size is the size of each element. The array must be arranged in the ascending order in respect to the compare function indicated by compar (last argument). Define the compare function indicated by compar to have two arguments. If the first argument is less than the second, a negative integer must be returned as the result. If the two arguments coincide, zero must be returned. If the first is greater than the second, a positive integer must be returned.

[Example]

#include    <stdlib.h>
#include    <string.h>
int compar(const void *x, const void *y);
 
void func(void) {
        static  char    *base[] = {"a", "b", "c", "d", "e", "f"};
        char            *key = "c";     /*Search key is "c".*/
        char            **ret;
                                        /*Pointer to "c" is stored in ret.*/
        ret = (char **) bsearch((char *) &key, (char *) base, 6, sizeof(char *), compar);
}
int compar(const void *x, const void *y) {
        return(strcmp(x, y));           /*Returns positive, zero, or negative integer as
                                        result of comparing arguments.*/
}