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

String Binary Search :

Searching a string using binary search algorithm is something tricky when compared to searching a number. Because we can compare 2 numerics directly, but in the case of strings it’s not as simple as number comparison.

Here we will see how we can do this in Binary Search.

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

Element to find: String key = “CCC”;

BinarySearchString.java
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 🙂