Java Array Binary Search
Syntax
public static int binarySearch(Object[] a, Object key)
Array used in binarySearch must be sorted. The binarsearch() method with Unsorted arrays give wrong
result. Array having duplicate elements when searched by binarySearch() function may return any of the duplicate element.
Following example demonstrates how to do a binary search on the Java array object
import java.util.Arrays;
public class binary_search {
public static void main(String[] args) {
int ar1[]={2,44,5,66,78,90,23,66};
int p, key=78;
p=Arrays.binarySearch(ar1, key);
System.out.println("element found at index "+p);
Arrays.sort(ar1);
p=Arrays.binarySearch(ar1, key);
System.out.println("element found at index "+p);
}
}
Output
element found at index 4
element found at index 6
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.