The bsearch function is used to search an element (refered to as the key) in an array. The algorithm used is binary search, and therefore it assumes that the array is already ordered. If the key is found, bsearch returns the position in the array in which it was found.

The qsort function requires five arguments. The first argument is a pointer to a variable containing the key we are searching in the array. The second argument is a pointer to the array that will be searched by the function. The third argument is the number of elements in the array. The fourth argument is the memory size of each element, and is usually computed using the sizeof operator. Finally, the fifth parameter is a pointer to a function that is used for comparison purposes.

Similarly to the qsort function, the comparison function must have the following signature:

int func(const void *, const void *);

The comparison function receives two parameters. They are the elements that need to be compared. They are received as void pointers because qsort doesn\'t know what is the type of the objects that are being compared. Thus, we need to convert these pointers into pointers to the data type used in the original array.

The return value of the comparison function is similar to the return value of strcmp. It should return 0 if the elements are the same, -1 if the first element is less than the second, and 1 otherwise.

The following code shows an example of bsearch in use:


#define NUM_INT 10
int a[NUM_INT] = { 0, 1, 2, 5, 3, 4, 6, 7, 8, 9 };

int compare(const void *a, const void *b)
        return *(int*)a - *(int*)b;

The output of this program is:

the position is 5
Article created on 2008-08-19 21:45:12

Post a comment