static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)
描述 (Description)
java.util.Arrays.binarySearch(T[] a, T key, int fromIndex, int toIndex, Comparator《? super T》 c)方法使用二进制搜索算法在指定数组的范围内搜索指定对象。 在进行此调用之前,必须根据指定的比较器将范围按升序排序。 如果未排序,则结果未定义。
声明 (Declaration)
以下是java.util.Arrays.binarySearch(super,index)方法的声明
public static <T> int binarySearch(T[] a, T key, int fromIndex, int toIndex, Comparator<? super T> c)
参数 (Parameters)
a - 这是要搜索的数组。
fromIndex - 要搜索的第一个元素(包括)的索引。
toIndex - 要搜索的最后一个元素(不包括)的索引。
key - 这是要搜索的值。
c - 这是排序数组的比较器。 空值表示应使用元素自然排序。
返回值 (Return Value)
如果搜索关键字的索引包含在指定范围内的数组中,则此方法返回索引; 否则,( - (插入点) - 1)。 插入点定义为键将插入到数组中的点:范围中第一个元素的索引大于键,或者如果范围中的所有元素都小于指定键,则为toIndex。
异常 (Exception)
ClassCastException - 如果范围包含使用指定的比较器不可相互比较的元素,或者搜索键与使用此比较器的范围中的元素不可比。
IllegalArgumentException - 如果fromIndex“toIndex
ArrayIndexOutOfBoundsException - 如果fromIndex“0或toIndex”a.length
例子 (Example)
以下示例显示了java.util.Arrays.binarySearch(super,index)方法的用法。
package com.iowiki;
import java.util.Arrays;
import java.util.Comparator;
public class ArrayDemo {
public static void main(String[] args) {
// initializing unsorted short array
Short shortArr[] = new Short[]{5, 2, 15, 52, 10};
// use comparator as null, sorting as natural ordering
Comparator<Short> comp = null;
// sorting array
Arrays.sort(shortArr, comp);
// let us print all the elements available in list
System.out.println("The sorted short array is:");
for (short number : shortArr) {
System.out.println("Number = " + number);
}
// 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);
// search between index 0 and 3, where searchVal doesn't exist
retVal = Arrays.binarySearch(shortArr, 0, 3, searchVal, comp);
System.out.println("The index of element 15 is : " + retVal);
}
}
让我们编译并运行上面的程序,这将产生以下结果 -
The sorted short array is:
Number = 2
Number = 5
Number = 10
Number = 15
Number = 52
The index of element 15 is : 3
The index of element 15 is : -4