Binary Search a String in C++



The binary search algorithm works on the divide-and-conquer principle as it keeps dividing the array in half before searching. To search for an element in an array using binary search, it should be sorted.

In the sorted array, we find the middle element and compare it with the element that has to be searched, and based on the comparison, we either search in the left or right sub-array or return the middle element.

In this article, we are given a sorted array of strings, and our task is to search for the given string using a binary search algorithm. Here are some example scenarios:

Scenario 1

Input: str[] = {"apple", "banana", "cherry", "grape", "orange"}, target = "grape"
Output: Element "grape" found at index: 3

Scenario 2

Input: str[] = {"cat", "dog", "elephant", "lion", "tiger"}, target = "fish"
Output: Element "fish" not found

Lexicographical Order of String

The lexicographical order refers to the arrangement of words in dictionary order of words. For example, 'apple' is lexicographically smaller than 'boy', and 'tutorial' is lexicographically greater than 'geek'.

Binary Searching on a String

The approaches to search a given string using binary search are given below:

Using Iteration

Below are the steps to search for a given string using binary search with an iterative approach:

  • Define a binSearch() function that accepts a string array, the size of the array, and the target string that you want to search.
  • Then calculate the middle index of the array.
  • Compare the target string with the middle element using an if-else statement. Return the middle element if the target is found at the middle index.
  • If the target is not available at the middle index, then check if it is lexicographically greater or less than the middle element.
  • If the target is lexicographically greater than the middle element, then set the left index to mid + 1 and search in the right half of the array.
  • If the target is lexicographically less than the middle element, then set the right index to mid - 1 and search in the left half of the array.
  • Repeat the above four steps until the left index becomes greater than the right index. If the element is found, return the index; otherwise, return element not found.

Example

Here is an example code implementing the above-mentioned steps for searching "grape" in the given array of strings.

#include <iostream>
#include <string>
using namespace std;
int binSearch(string str[], int n, string target)
{
   int left = 0, right = n - 1;
   while (left <= right)
   {
      int mid = left + (right - left) / 2;
      if (str[mid] == target)
         return mid;
      else if (str[mid] < target)
         left = mid + 1;
      else
         right = mid - 1;
   }
   return -1; 
}
int main()
{
   string str[] = {"apple", "banana", "cherry", "grape", "orange"};
   int n = sizeof(str) / sizeof(str[0]);
   string target = "grape";
   cout << "Given array: ";
   for (int i = 0; i < n; i++)
   {
      cout << str[i] << " ";
   }
   cout << endl;
   cout << "Target String to search: " << target 
        << endl;
   int result = binSearch(str, n, target);
   cout << "Element found at index: " 
        << result << endl;
   return 0;
}

The output of the above code is as follows:

Given array: apple banana cherry grape orange 
Target String to search: grape
Element found at index: 3

Using Recursion

The following are the steps to search a string with binary search using recursion:

  • Define a binSearch() function that accepts the string array, the left index, the right index, and the target string that you want to search.
  • Calculate the middle index of the array and compare the target string with the middle element using an if-else statement. Return the middle index if the target string is found at the middle index.
  • If the target string is not available at the middle index, then check if it is lexicographically greater or less than the middle element.
  • If the target string is lexicographically greater than the middle element, then recursively call the binSearch() function by setting the left index as mid + 1 and searching in the right half of the array.
  • If the target string is lexicographically less than the middle element, then recursively call the binSearch() function by setting the right index as mid - 1 and searching in the left half of the array.
  • Repeat the above four steps until the left index becomes greater than the right index. If the element is found, return the index otherwise, return element not found.

Example

The following is an example code implementing the above-mentioned steps to search for "elephant" in the given string array with binary search using recursion.

#include <iostream>
#include <string>
using namespace std;
int binSearch(string str[], int left, int right, string target)
{
   if (left > right)
      return -1;
   int mid = left + (right - left) / 2;
   if (str[mid] == target)
      return mid;
   else if (str[mid] < target)
      return binSearch(str, mid + 1, right, target);
   else
      return binSearch(str, left, mid - 1, target);
}
int main()
{
   string str[] = {"cat", "dog", "elephant", "lion", "tiger"};
   int n = sizeof(str) / sizeof(str[0]);
   string target = "elephant";
   cout << "Given string: ";
   for (int i = 0; i < n; i++)
   {
      cout << str[i] << " ";
   }
   cout << endl;
   cout << "Target String to search: " << target 
        << endl;
   int result = binSearch(str, 0, n - 1, target);
   cout << "Element found at index: " 
        << result << endl;
   return 0;
}

The output of the above code is as follows:

Given string: cat dog elephant lion tiger 
Target String to search: elephant
Element found at index: 2

Using binary_search() Function

In this approach, we have used the STL function binary_search() of the <algorithm> header. It accepts the starting index str, the index up to which we want to search an element, i.e, str+n, and the target string that we want to search. It implements binary search and finds the given string.

Example

In this example, we have used the binary_search() function to search for "mango" in the given array of strings with binary search:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
   string str[] = {"apple", "banana", "kiwi", "mango", "pineapple"};
   int n = sizeof(str) / sizeof(str[0]);
   string target = "mango";
   cout << "Given strings: ";
   for (int i = 0; i < n; i++)
   {
      cout << str[i] << " ";
   }
   cout << endl;
   cout << "Target String to search: " << target << endl;
   bool result = binary_search(str, str + n, target);
   if (result)
      cout << "Element Found" << endl;
   else
      cout << "Not Found" << endl;
   return 0;
}

The output of the above code is as follows:

Given strings: apple banana kiwi mango pineapple 
Target String to search: mango
Element Found

Complexity Comparison

Here is a comparison of the time and space complexity of all the above approaches.

Approach Time Complexity Space Complexity
Iterative Technique O(m log n) O(1)
Recursive Approach O(m log n) O(log n)
binary_search() Function O(m log n) O(1)
Updated on: 2025-08-06T19:01:28+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements