std::binary_search() is a C++ STL algorithm used to efficiently check whether a specific value exists in a sorted range. It is defined in the <algorithm> header and works with arrays and STL containers such as vector and set.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 3, 6, 8, 9};
int k = 8;
if (binary_search(v.begin(), v.end(), k))
cout << k << " is Present";
else
cout << k << " is NOT Present";
return 0;
}
Output
8 is Present
Syntax
std::binary_search(first, last, k, comp);
Parameters
- first: Iterator to the first element of the range.
- last: Iterator to the theoretical element just after the last element of range.
- k: The value to be search.
- comp: Custom comparison function that defines the ordering of elements. By default, std::less<T> is used.
Return Value
- Returns true, if k is present in the given range.
- Returns false, if k is not present in the given range.
Note: Behaviour of binary_search() is undefined if the given range is not sorted as binary search algorithm can only be implemented on sorted data.
The following examples demonstrates the different use cases of std::binary_seach() function:
Example 1: Checking if an Element Exists in Array using std::binary_search()
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 4, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 7;
// Check if the element exists
if (binary_search(arr, arr + n, k))
cout << k << " is Present";
else
cout << k << " is NOT Present";
return 0;
}
Output
7 is Present
Explanation: This program uses std::binary_search() to check whether the value 7 exists in a sorted integer array and prints whether it is present or not.
Example 2: Using binary_search() on a Set Container
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {1, 4, 5, 7, 9};
int k = 8;
// Check if the element exists
if (binary_search(s.begin(), s.end(), k))
cout << k << " is Present";
else
cout << k << " is NOT Present";
return 0;
}
Output
8 is NOT Present
Explanation: Even though set container does not have random access, binary_search() function still works because of the reason discussed below.