Open In App

Search String using binary_search() function in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

The in-built STL library function binary_search() for searching whether a given string is present or not in the given string array. Binary search is a divide and conquers approach. The idea behind the binary search algorithm is to keep dividing the array in half until the element is found, or all the elements are exhausted. The middle item of the array is compared with the target value i.e. the value that needs to be searched, if it matches, it returns true otherwise if the middle term is greater than the target, the search is performed in the left sub-array. If the middle item is less than the target, the search is performed in the right sub-array.

Example:

Input: arr[] = {“Geeks”, “For”, “GeeksForGeek”}
Search “Geeks”
Output: String Founded in array

Syntax:

binary_search(starting_address, ending_address, value_of_string)

Below is the implementation of the above approach:

C++14




// C++ program to implement Binary
// Search in Standard Template Library (STL)
#include <algorithm>
#include <iostream>
using namespace std;
 
void show_array(string arr[], int arraysize)
{
    for (int i = 0; i < arraysize; i++)
        cout << arr[i] << ", ";
}
 
void binarySearch(string arr[], int size)
{
    cout << "\nThe array is : \n";
    show_array(arr, size);
 
    // Sort string array a for binary search as prerequisite
    sort(arr, arr + size);
 
    // Finding for "Geeks"
    cout << "\n\nSearching Result for \"Geeks\"";
    if (binary_search(arr, arr + size, "Geeks"))
        cout << "\nString Founded in array\n";
    else
        cout << "\nString not Founded in array\n";
 
    // Finding for string str
    string str = "Best";
    cout << "\nSearching Result for \"Best\"";
    if (binary_search(arr, arr + size, str))
        cout << "\nString Found in array";
    else
        cout << "\nString not Found in array";
}
 
// Driver code
int main()
{
    // Initialising string array a
    string arr[] = { "Geeks", "For", "GeeksForGeek" };
 
    // Find size of array arr
    int size = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    binarySearch(arr, size);
 
    return 0;
}


Output: 

The array is : 
Geeks, For, GeeksForGeek, 

Searching Result for "Geeks"
String Founded in array

Searching Result for "Best"
String not Found in array

 

Time Complexity: O(N*log N), where N represents the number of elements present in the array

Auxiliary Space: O(1)



Last Updated : 31 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads