Q:

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

belongs to collection: C++ programs on various topics

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Stack program using C++ Standard Template Library ... >>
<< Sort an array in descending order using sort() fun...