Standard C Functions


bsearch


Syntax

#include <stdlib.h>
void *bsearch(const void *key, const void *base, size_t num, size_t width, 
              int (*compare)(const void *, const void *));
Arguments
key        key to be found
base       pointer to the array to be found
num        number of elements in the array to be found
width      size of one element in the array (byte unit) to be found
compare    pointer to the comparison function created by the user

Return Value

A pointer to the elements that were found, or NULL if nothing is found 

Description

Using a binary search, it finds an element that matches the key argument in an array sorted in ascending order. If the array is not in ascending order, the key can't be found.

The compare argument points to the comparison function that you create in the following form:

int compare(const void *elem1, const void *elem2);

The value returned by the comparison function is:

less than zero    --> elem1 is less than elem2
equal to zero     --> elem1 is equal to elem2
greater than zero --> elem1 is greater than elem2