A pointer to a constant memory location of unspecified type. The pointed-to data cannot be modified through this pointer.
1st Parameter
Pointer to the element being searched for
2nd Parameter Type : const void *
A pointer to a constant memory location of unspecified type. The pointed-to data cannot be modified through this pointer.
2nd Parameter
Pointer to the first element of the array being searched
3rd Parameter Type : size_t
Platform-specific unsigned type for array indices and memory sizes.
3rd Parameter
Number of elements in the array
4th Parameter Type : size_t
Platform-specific unsigned type for array indices and memory sizes.
4th Parameter
Size of each element in the array in bytes
5th Parameter Type : int (*)(const void *, const void *)
Pointer to a function that takes two constant void pointers as arguments and returns an integer, typically used to compare two elements.
5th Parameter
Pointer to a comparison function that defines the ordering of elements
Read more about parameters of bsearch in parameters section
The bsearchfunction in C language Performs binary search over an array.
The bsearch function searches an array of nmemb objects, the initial member of which is pointed to by base, for a member that matches the object pointed to by key. The size of each member is specified by size. The contents of the array should be in ascending sorted order according to the comparison function pointed to by compar. The function returns a pointer to a matching member of the array, or a null pointer if no match is found.
The bsearchfunction takes 5
parameters:
•
const void * `key`: Pointer to the element being searched for
•
const void * `base`: Pointer to the first element of the array being searched
•
size_t `nmemb`: Number of elements in the array
•
size_t `size`: Size of each element in the array in bytes
•
int (*)(const void *, const void *) `compar`: Pointer to a comparison function that defines the ordering of elements
Performs a binary search on a sorted array to find an element matching the key, using the comparison function to determine equality.
The bsearch function return value :
Returns a pointer to the matching element if found, or NULL if not found
Output
This example demonstrates the basic usage of the `bsearch` function to search for an integer in a sorted array of integers.