Searching in STL C++

About Searching in STL

Searching is defined as finding the element in group of elements arranged in the particular order. Searching in STL is done by inbuilt function binary_search().

Searching in stl

Syntax of binary_search() :

binary_search(start_address, end_address, element to be find);

This algorithm’s primary principle is to divide an array in half repeatedly (divide and conquer) until either the element is located or all the elements have been used up. It operates by comparing the middle item in the array with our target; if they match, it returns true; if they don’t, the left sub-array is searched. The search is carried out in the appropriate sub-array if the middle term is less than the target element.

Array must be sorted to apply binary search in stl

Example of Searching in STL :

Run
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    int arr[] = {2,4,3,43,4,35,67,99,85,34};
    int n = sizeof(arr)/sizeof(arr[0]);
    int a = 43;
    sort(arr, arr+n);
    if(binary_search(arr, arr+n, a)){
        cout<<"Element " << a<<" is present in the array";
    }
    else{
        cout<<"Element " << a <<" is not found in the array";
    }
    return 0;
}

Output :

Element 43 is present in the array

In the above program, we take the array and used sort function to sort the elements , by using binary_search we check elements a is present in the array or not.

Example of Searching in STL:

Run
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    int arr[] = {2,4,3,43,4,35,67,99,85,34};
    int n = sizeof(arr)/sizeof(arr[0]);
    int a = 100;
    sort(arr, arr+n);
    if(binary_search(arr, arr+n, a)){
        cout<<"Element " << a<<" is present in the array";
    }
    else{
        cout<<"Element " << a <<" is not found in the array";
    }
    return 0;
}

Output :

Element 100 is not found in the array

In the above program, we take the array and used sort function to sort the elements , by using binary_search we check elements a is present in the array or not.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription