Java Arrays.binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator <? super T> c)
Syntax
Arrays.binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator <? super T> c) has the following syntax.
public static <T> int binarySearch(T[] a,
int fromIndex,
int toIndex,
T key,
Comparator <? super T> c)
Example
In the following code shows how to use Arrays.binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator <? super T> c) method.
Binary search needs sorted arrays.
import java.util.Arrays;
import java.util.Comparator;
/*w ww.jav a2 s . co m*/
public class Main {
public static void main(String[] args) {
// initializing sorted short array
Short shortArr[] = new Short[]{1, 2, 15, 52, 110};
// use comparator as null, sorting as natural ordering
Comparator<Short> comp = null;
// entering the value to be searched
short searchVal = 15;
// search between index 1 and 4
int retVal = Arrays.binarySearch(shortArr, 1, 4, searchVal, comp);
System.out.println("The index of element 15 is : " + retVal);
}
}
The code above generates the following result.
Home »
Java Tutorial »
java.util »
Java Tutorial »
java.util »