![]() |
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. Syntax of bsearch() in Cvoid* bsearch(key, base, num, size, compare); Parameters of bsearch()The bsearch() function takes five parameters:
Return Value of bsearch()The bsearch() function returns two values:
bsearch() Comparator FunctionThe comparator function is passed as a parameter to the bsearch() function and it contains the logic to find the matching element. Signature of Comparator Functionint 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:
Example of bsearch() in CThe below example demonstrates how we can search an element using bsearch() in C.
Output 3 Found at index 2 Time Complexity: O(log N), where n is the number of elements in the array. |
Reffered: https://www.geeksforgeeks.org
C Language |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |