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
#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(arr, arr + size);
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" ;
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" ;
}
int main()
{
string arr[] = { "Geeks" , "For" , "GeeksForGeek" };
int size = sizeof (arr) / sizeof (arr[0]);
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
Share your thoughts in the comments
Please Login to comment...