Java String Binary Search Example

By | 2018-08-04T15:51:41+00:00 June 17th, 2018|java|0 Comments

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 🙂

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