The binary_search()
function is available in the <algorithm.h>
header file in C++. This function helps you perform binary search operations on a list of elements. As you may already know, the binary search algorithm works only on a sorted list of elements.
The binary_search
accepts the following parameters.
first
: This parameter specifies the start index of the array or vector where you want to search.
last
: This parameter specifies the end index of the array or vector where you want to search.
val
: This is the value that you want to search for.
comp
: This is an optional parameter used to compare the values in the array. This can be used if we want to compare the values in a custom way.
The binary_search()
function returns a Boolean value. It returns true
if the value is present in the array or vector and false
if the value is not present.
Let’s look at the code now.
#include <iostream>#include <algorithm>#include <vector>using namespace std;int main() {vector<int> v = {1,2,3,4,5,4,3,2,1};std::sort (v.begin(), v.end());int num = 3;cout << "Searching for " << num << ": ";if (binary_search (v.begin(), v.end(), num))cout << "Found!\n";elsecout << "Not found";return 0;}
sort()
function.binary_search()
function, and then print whether the num
is found inside the vector not.In this way, we can use the built-in binary_search()
function to avoid the extra time to write the logic from scratch. This helps immensely in coding contests.