Tuesday, November 26, 2024
Google search engine
HomeData Modelling & AISearch String using binary_search() function in C++ STL

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

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)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments