binary_search

binary_search(start_ptr, end_ptr, num): This function returns true if the element is present in the container, else returns false. The start_ptr variable holds the starting point of the binary search and end_ptr holds the ending position of binary search space and num is the value to be found.

Coding implementation of binary_search function: 

CPP




// C++ code to demonstrate the working of binary_search()
 
#include <bits/stdc++.h>
using namespace std;
 
// Driver's code
int main()
{
    // initializing vector of integers
    vector<int> arr = { 10, 15, 20, 25, 30, 35 };
 
    // using binary_search to check if 15 exists
    if (binary_search(arr.begin(), arr.end(), 15))
        cout << "15 exists in vector";
    else
        cout << "15 does not exist";
 
    cout << endl;
 
    // using binary_search to check if 23 exists
    if (binary_search(arr.begin(), arr.end(), 23))
        cout << "23 exists in vector";
    else
        cout << "23 does not exist";
 
    cout << endl;
}


Output

15 exists in vector
23 does not exist

Time Complexity: O(log N) – where N is the number of elements in the array.
Auxiliary Space: O(1)

Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)

Binary search is an important component in competitive programming or any algorithmic competition, having knowledge of shorthand functions reduces the time to code them. Binary search is the most efficient search algorithm.

Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log N). 

General operations performed using binary search:

  1. finding an element
  2. lower_bound 
  3. upper_bound

Similar Reads

1. binary_search:

binary_search(start_ptr, end_ptr, num): This function returns true if the element is present in the container, else returns false. The start_ptr variable holds the starting point of the binary search and end_ptr holds the ending position of binary search space and num is the value to be found....

2. lower_bound:

...

3. upper_bound:

lower_bound(start_ptr, end_ptr, num):Returns pointer to the position of num if the container contains only one occurrence of num. Returns a pointer to the first position of num if the container contains multiple occurrences of num. Returns pointer to the position of a number just higher than num, if the container does not contain an occurrence of num which is the position of the number when inserted in the already sorted array and sorted again. Subtracting the first position i.e vect.begin() from the pointer, returns the actual index. The start_ptr variable holds the starting point of the binary search and end_ptr holds the ending position of binary search space and num is the value to be found....