C library function -bsearch()
C Standard Library - <stdlib.h>
bsearch is a function in the C standard library, used to perform a binary search in a sorted array. Its definition is in the stdlib.h header file.
C Library Functionsvoid *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))PairnitemsPerform a binary search on an array of objects,basePoints to the array being searched,keyPoints to the element to be searched for,sizeSpecifies the size of each element in the array.
The contents of the array should be sorted in ascending order according tocomparthe corresponding comparison function.
Declaration
The following is the declaration of the bsearch() function.
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
Parameter
key: Pointer to the target element to be searched for.base: Pointer to the starting position of the array.nmemb: Number of elements in the array.size: The size of each element (in bytes).compar: Pointer to the comparison function, which is used to compare two elements.
Return Value
- If a matching element is found,
bsearchreturn a pointer to that element. - If no matching element is found,
bsearchreturnNULL。
Comparison function
The comparison function must match the following signature:
int compar(const void *a, const void *b);
Function returns:
- A negative value, if
aless thanb。 - Zero, if
aequalsb。 - A positive value, if
agreater thanb。
Example
The following example demonstrates the usage of the bsearch() function.
Example
Let us compile and run the above program, which will produce the following result:
Found item = 32other extensions