binary_search function in C++ STL

The binary_search is a commonly used basic function of C++ Standard Library for doing searching. It uses a searching algorithm that requires the array to be sorted before search is applied. The algorithm used uses the divide and conquer technique that divides the array in half ans search for the element.

Syntax

binary_search(startingAddress, sndingAddress, searchingElement)

Parameter: The binary_search function acceots the following parameters which are given below:

  1. startingAddress: This parameter is the address of the starting element of the array.
  2. sndingAddress: This parameter is the address of the ending element of the array.
  3. searchingElement: This parameter is the target element which is to be searched.

Return value: The binary_search function return 1 if Searching_Element is found in the array, otherwise 0.

Internal Functioning

The binary_search() function works by comparing Searching_Element with the middle elemet of the array. There are condition to be follow:

  • If match found, it returns true.
  • If the middle term is greater than the target, left sub-array is taken for searching.
  • If the middle term is less than target, right sub-array is taken for searching.

Example of binary_search() Function

#include <iostream> 
#include <algorithm> 
  
using namespace std; 
  
void print_array(int data[], int n) 
{ 
    for(int i = 0; i < n; ++i) 
        cout << data[i] << " "; 
} 
  
int main() 
{ 
    int data[] = {1, 5, 8, 9, 6}; 
    
    int n = sizeof(data) / sizeof(data[0]);
    
    cout << "Array : "; 
    print_array(data, n); 
    
    sort(data, data+n); 
    
    if (binary_search(data, data+n, 1)){
        cout <<"\n\nElement Found";
    }
    else{
        cout <<"\n\nElement Not Found";
    }
  
    return 0; 
  
} 

Output

Array : 1 5 8 9 6 
Element Found

This article is written by

Pratik Singhal

Pratik Singhal

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top