Binary Search a String in C++


In Binary search a string, we are given a sorted array of strings and we have to search for a string in the array of strings using binary search algorithm.

Example

Input : stringArray = {“I”, “Love”, “Programming”, “tutorials”, “point”}.
Element = “programming”
Output : string found at index 3
Explanation : The index of string is 3.
Input : stringArray = {“I”, “Love”, “Programming”, “tutorials”, “point”}.
Element = “coding”
Output : -1 ‘string not found’

Binary search is searching technique that works by finding the middle of the array for finding the element.

For array of strings also the binary search algorithm will remain the same. But the comparisons that are made will be based on string comparison. String comparison check for the first character of the strings and compare it. characters are same then it goes to the next and so on.

Algorithm

arrString : array of sorted strings
Lower = 0 ; upper = n (length of array)
Element = string that is to be found
Step 1 : while element is not found. Do :
Step 2 : mid = lower + (upper - lower) / 2 ;
Step 3 : if arrString[mid] = element , return mid and exit
Step 4 : if arrString[mid] < element, lower = mid+1
Step 5 : if arrString[mid] > element, upper = mid-1
Step 6 : upper < lower , return -1, exit.

Example

#include<bits/stdc++.h>
using namespace std;
int binarySearchString(string arr[], string x, int n) {
   int lower = 0;
   int upper = n - 1;
   while (lower <= upper) {
      int mid = lower + (upper - lower) / 2;
      int res;
      if (x == (arr[mid]))
         res = 0;
      if (res == 0)
         return mid;
      if (x > (arr[mid]))
         lower = mid + 1;
      else
         upper = mid - 1;
   }
   return -1;
}
int main () {
   string arr[] = {"I", "Love", "Programming" , "tutorials" , "point"};
   string x = "Programming";
   int n = 4;
   int result = binarySearchString(arr, x, n);
   if(result == -1)
      cout<<("Element not present");
   else
      cout<<("Element found at index ")<<result;
}

Output

Element found at index 2

Updated on: 09-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements