Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

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

  • Last Updated : 20 Jul, 2021

The in-built STL library function binary_search() for searching 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:

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
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)
Auxiliary Space: O(1)



My Personal Notes arrow_drop_up
Recommended Articles
Page :