static int binarySearch(char[] a, int fromIndex, int toIndex, char key)
描述 (Description)
java.util.Arrays.binarySearch(char[] a, int fromIndex, int toIndex, char key)方法使用二进制搜索算法在指定的字符数组范围内搜索指定值。 必须在进行此调用之前对范围进行排序。如果未对其进行排序,则结果未定义。
声明 (Declaration)
以下是java.util.Arrays.binarySearch()方法的声明
public static int binarySearch(char[] a, int fromIndex, int toIndex, char key)
参数 (Parameters)
a - 这是要搜索的数组。
fromIndex - 这是要搜索的第一个元素(包括)的索引。
toIndex - 这是要搜索的最后一个元素(不包括)的索引。
key - 这是要搜索的值。
返回值 (Return Value)
此方法返回搜索键的索引(如果它包含在数组中),否则返回( - (插入点) - 1)。 插入点是密钥插入阵列的点; 范围中第一个元素的索引大于键,或者如果范围中的所有元素都小于指定键,则为toIndex。
异常 (Exception)
IllegalArgumentException - 如果fromIndex“toIndex
ArrayIndexOutOfBoundsException - 如果fromIndex“0或toIndex”a.length
例子 (Example)
以下示例显示了java.util.Arrays.binarySearch()方法的用法。
package com.iowiki;
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing unsorted char array
char charArr[] = {'a', 'c', 'b', 'e','d'};
// sorting array
Arrays.sort(charArr);
// let us print all the elements available in list
System.out.println("The sorted char array is:");
for (char number : charArr) {
System.out.println("Number = " + number);
}
// entering the value to be searched
char searchVal = 'e';
// entering the range of index
int retVal = Arrays.binarySearch(charArr,1,5,searchVal);
System.out.println("The index of e is : " + retVal);
}
}
让我们编译并运行上面的程序,这将产生以下结果 -
The sorted char array is:
Number = a
Number = b
Number = c
Number = d
Number = e
The index of e is : 4