Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
binarysearch
communitycreator

How to use the built-in binary_search() function in C++

Harsh Jain

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.

Parameters

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.

Return

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.

Code

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"; 
  else 
    cout << "Not found";
    
  return 0;
}
Use binary_search() function in C++

Explanation

  • From lines 1 to 3, we import the required header files.
  • In line 8, we create a vector of integer elements.
  • In line 9, we sort the vectorSorting is required because binary search works only on a sorted list of elements. with the built-in sort() function.
  • In line 13, we call the 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.

RELATED TAGS

c++
binarysearch
communitycreator
RELATED COURSES

View all Courses

Keep Exploring