std::bsearch searches for an element in a sorted array. Finds an element equal to element pointed to by key in an array pointed to by ptr.
If the array contains several elements that comp would indicate as equal to the element searched for, then it is unspecified which element the function will return as the result.
void* bsearch( const void* key, const void* ptr, std::size_t count, std::size_t size, * comp ); Parameters : key - element to be found ptr - pointer to the array to examine count - number of element in the array size - size of each element in the array in bytes comp - comparison function which returns ?a negative integer value if the first argument is less than the second, a positive integer value if the first argument is greater than the second and zero if the arguments are equal. Return value : Pointer to the found element or null pointer if the element has not been found.
Implementing the binary predicate comp :
4 found at position 3 9 not found
Where to use :Binary search can be used on sorted data where a key is to be found. It can be used in cases like computing frequency of a key in a sorted list.
Why Binary Search?
Binary search is much more effective than linear search because it halves the search space at each step. This is not significant for our array of length 9. Here, linear search takes at most 9 steps and binary search takes at most 4 steps. But consider an array with 1000 elements, here linear search takes at most 1000 steps, while binary search takes at most 10 steps.
For 1 billion elements, binary search will find our key in at most 30 steps.
Related Article: std::binary_search
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.