Home » C++ STL

Binary Search in C++ using Standard Template Library (STL) function binary_search()



In this article, we are going to learn how to search an element from an array using binary_search() function of C++ Standard Template Library (STL)?
Submitted by IncludeHelp, on January 04, 2018

Given an array and we have to search an element using binary_search(), which is a function of algorithm header of C++ Standard Template Library.

binary_search() function

It is a built-in function, which is used to search an element from an array using Binary Search Algorithm.

Syntax:

binary_search(start_address, end_address, element_to_search);

Here,

  1. start_address - starting array element’s pointer
  2. end_address - ending array element’s pointer
  3. element_to_search - element to search

Steps:

  1. Declare and define an array
  2. Sort the array (here, we are using sort() function to sort array in ascending order).
  3. Find the element using binary_search() function.
  4. Print the message with its index if it exists.

Program to implement Binary Search using C++ STL

#include <iostream>
#include <algorithm>

using namespace std;
 
//function to display array list
void dispArray(int arr[], int size)
{
    for(int i = 0; i < size; i++)
        cout <<" "<< arr[i];
    cout<<endl;
}
 

//main code for binary search 
int main()
{
    int a[]= {10, 1, 20, 2, 30, 4};
    
    //get array length
    int arr_length = sizeof(a) / sizeof(int);
    
    //print array
    cout<<"Array elements are: ";
    dispArray(a, arr_length);
 
    //sort the array
    sort(a, a + arr_length);
    cout<<"Sorted array elements: ";
    dispArray(a, arr_length);
    
    //searching 30 in the array
    if(binary_search(a, a+ arr_length, 30))
        cout<<"Element found"<<endl;
    else
        cout<<"Element does not found"<<endl;
        
    return 0;
}

Output

Array elements are:  10 1 20 2 30 4
Sorted array elements:  1 2 4 10 20 30
Element found





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.