Algoritma Binary Search Sebuah String

Omjebs > Tech > Algoritma Binary Search Sebuah String
laptop office internet technology

Algoritma Binary Search Sebuah String

Contoh:

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.

Code:

// 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); 
	} 
} 

Output:

Element found at index 2
0 0 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x