Java String Binary Search Example

By | 2018-06-25T03:10:16+00:00 June 17th, 2018|java|0 Comments

Here we are going to find a specific element in a string array using String Binary Search Algorithm.

String Binary Search :

Searching a string using binary search algorithm is something tricky, comparing to searching a number. Because we can compare 2 numbers directly, but in case of Strings its not as simple as number comparison.

Here I am going to show you how we can do this in Binary Search.

Input: String[] a = { “AAA”, “BBB”, “CCC”, “DDD”, “EEE”, “FFF”, “GGG” };

Element to find: String key = “CCC”;

Output: Key Found at : 2 position

public class BinarySearchString {
  
  static String[] a = { "AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG" };
  static int min = 0;
  static int max = a.length - 1;
  static int mid;
  static String key = "CCC";
  
  public static void main(String[] args) {
    System.out.println("Key Found at : "+stringBinarySearch()+" position");
  }

  public static int stringBinarySearch() {
    while (min <= max) {
      mid = (min + max) / 2;
      if(a[mid].compareTo(key) < 0) {
        min = mid+1;
      }else if(a[mid].compareTo(key) > 0){
        max = mid-1;
      }else {
        return mid;
      }
    }
    return -1;
  }
}

Output:

Key Found at : 2 position

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment