![]() |
VOOZH | about |
In C programming language, bsearch() function is used to perform a binary search on a sorted array to search for an element. The name bsearch stands for “binary search” which is an efficient algorithm for finding an item from a sorted list of items. It is defined inside the stdlib.h header file.
void* bsearch(key, base, num, size, compare);
The bsearch() function takes five parameters:
The bsearch() function returns two values:
The comparator function is passed as a parameter to the bsearch() function and it contains the logic to find the matching element.
int comparatorName(const void* ptr1, const void* ptr2);Here, ptr1 and ptr2 are the pointers to the elements to be compared. All the comparator function should have the same signature.
The comparator function should return the result as:
The below example demonstrates how we can search an element using bsearch() in C.
3 Found at index 2
Time Complexity: O(log N), where n is the number of elements in the array.
Auxilliary Space: O(1)