Binary Search a String

Given a sorted array of String and a String x, find index of x if it is present in the array.

Examples:

Input :  arr[] = { "contribute", "geeks", "ide", "practice"}, x = "ide"
Output :  2
The String x is present at index 2.

Input :  arr[] = { "contribute", "geeks", "ide", "practice"}, x = "zz"
Output :  -1
The String "zz" is not present.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Prerequisites : Binary Search, String Comparison in Java

The idea is to compare x with middle string in the given array. If it matches, then return mid, else if it is smaller than mid, then search in left half, else search in right half.

C++

 // CPP program to implement Binary Search for strings #include using namespace std;        // Returns index of x if it is present in arr[],     // else return -1     int binarySearch(string arr[], string x,int n)     {         int l = 0 ;         int r = n - 1;         while (l <= r)          {             int m = l + (r - l) / 2;            int res;         if (x == (arr[m]))             res = 0;                               // Check if x is present at mid             if (res == 0)                 return m;                // If x greater, ignore left half             if (x > (arr[m]))                 l = m + 1;                // If x is smaller, ignore right half             else                 r = m - 1;         }            return -1;     }        // Driver code     int main()     {         string arr[] = { "contribute", "geeks", "ide", "practice"};         string x = "ide";         int n = 4;         int result = binarySearch(arr, x,n);            if (result == -1)             cout << ("Element not present");         else             cout << ("Element found at index ") << result;     }        // This code is contributed by // Shashank_Sharma

Java

 // Java program to implement Binary Search for strings class GFG {        // Returns index of x if it is present in arr[],     // else return -1     static int binarySearch(String[] arr, String x)     {         int l = 0, r = arr.length - 1;         while (l <= r) {             int m = l + (r - l) / 2;                int res = x.compareTo(arr[m]);                // Check if x is present at mid             if (res == 0)                 return m;                // If x greater, ignore left half             if (res > 0)                 l = m + 1;                // If x is smaller, ignore right half             else                 r = m - 1;         }            return -1;     }        // Driver method to test above     public static void main(String []args)     {         String[] arr = { "contribute", "geeks", "ide", "practice"};         String x = "ide";         int result = binarySearch(arr, x);            if (result == -1)             System.out.println("Element not present");         else             System.out.println("Element found at "                               + "index " + result);     } }

Python3

 # Python3 program to implement Binary  # Search for strings    # Returns index of x if it is present # in arr[], else return -1 def binarySearch(arr, x):     l = 0     r = len(arr)     while (l <= r):         m = l + ((r - l) // 2)            res = (x == arr[m])            # Check if x is present at mid         if (res == 0):             return m - 1            # If x greater, ignore left half         if (res > 0):             l = m + 1            # If x is smaller, ignore right half         else:             r = m - 1        return -1    # Driver Code if __name__ == "__main__":        arr = ["contribute", "geeks",                 "ide", "practice"];     x = "ide"     result = binarySearch(arr, x)        if (result == -1):         print("Element not present")     else:         print("Element found at index" ,                                  result)    # This code is contributed by ita_c

C#

 // C# program to implement Binary Search for strings     using System;    class GFG {         // Returns index of x if it is present in arr[],      // else return -1      static int binarySearch(String[] arr, String x)      {          int l = 0, r = arr.Length - 1;          while (l <= r) {              int m = l + (r - l) / 2;                 int res = x.CompareTo(arr[m]);                 // Check if x is present at mid              if (res == 0)                  return m;                 // If x greater, ignore left half              if (res > 0)                  l = m + 1;                 // If x is smaller, ignore right half              else                 r = m - 1;          }             return -1;      }         // Driver method to test above      public static void Main(String []args)      {          String[] arr = { "contribute", "geeks", "ide", "practice"};          String x = "ide";          int result = binarySearch(arr, x);             if (result == -1)              Console.WriteLine("Element not present");          else             Console.WriteLine("Element found at "                             + "index " + result);      }  // This code is contributed by Ryuga }

PHP

 0)             \$l = \$m + 1;            // If x is smaller, ignore right half         else             \$r = \$m - 1;     }        return -1; }    // Driver Code \$arr = array("contribute", "geeks",                  "ide", "practice"); \$x = "ide"; \$result = binarySearch(\$arr, \$x);    if (\$result == -1)     print("Element not present"); else     print("Element found at index " .                              \$result);    // This code is contributed by mits ?>

Output:

Element found at index 2

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.