bsearch() - Utility Function
How is Utility function "bsearch()" used in C++?
How to perform a Binary search in array?
Explanation
bsearch() is a Utility Function that does a binary search on a sorted array pointed by the pointer "*buf", then returns the pointer to first element that matches the "key" value of the table of "size". The number of elements of an array is specified by "num" value.
Syntax:
void *bsearch(const void *key, const void *buf,
size_t num, size_t size, int(*compare)
(const void *, const void *));
In the above syntax "compare" is used to compare the elements with the keys of an array. This function returns "0" if both arguments are equal, if "arg1" is less than "arg2" then a negative value is returned. If "arg1" is greater, then a positive value is returned by the function. The following is the syntax of this function.
Syntax:
int func_name(const void *arg1, const void *arg2);
Example :
#include <stdio.h> #include <stdlib.h> #include <string.h> char arr[][40] = {"1", "2", "3" }; int main () { char check[40] = "6"; qsort(arr, 3, 40, (int(*) (const void*, const void*))strcmp); char *find = (char*) bsearch(check, arr, 3, 40, (int(*)(const void*, const void*))strcmp); if (find) printf("The string "%s" is found.\n", find); else printf("The string "%s" not found.\n", check); return 0; } |
Result :
The string 6 not found
In the above example bsearch() is used to check if the string "6" is found in the array. Before doing a binary search the array "arr" is sorted using the "qsort" function.