Do you want to search for an element in a array in Java using Binary Search algorithm ? . If yes , its pretty much easy to do it using the binarySearch method exposed by the Arrays class.
How to search array elements in Java using Binary Search ?
Below is an example of searching an element using Binary search from array elements in Java.
package com.abundantcode;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args)
{
String[] input = {"Java", "Abundantcode.com", "MCA Lab Programs", "B.E Java Lab Programs", "BCA Java Programs"};
// Sort the Array
Arrays.sort(input);
String searchString = "Java";
// Call the Binary Search method of the Arrays class
int result = Arrays.binarySearch(input,0, input.length-1,searchString);
System.out.println(result);
}
}
Leave a Reply