Java.util.Arrays 类

java.util.Arrays.binarySearch() 方法用于在指定的字符数组范围内搜索使用二分搜索算法指定值。在进行此调用之前,必须对范围进行排序(通过 sort(char[], int, int) 方法)。如果未排序,则结果不确定。如果范围包含多个具有指定值的元素,则无法保证会找到哪一个。

语法

public static int binarySearch(char[] a, int fromIndex, 
                               int toIndex, char key)

参数

a 指定要搜索的数组。
fromIndex 指定要搜索的第一个元素(含)的索引。
toIndex 指定第一个元素的索引要搜索的最后一个元素(不包括)。
key 指定要搜索的值。

返回值

如果搜索关键字包含在指定范围内的数组中,则返回该索引;否则,(-(插入点) - 1)。插入点定义为将键插入数组的点:范围内第一个元素的索引大于键,如果范围内的所有元素都小于指定键,则为 toIndex。

异常

  • 抛出IllegalArgumentException,如果fromIndex > toIndex
  • 抛出ArrayIndexOutOfBoundsException,如果fromIndex < 0 或 toIndex > a.length

示例:

在下面的示例中,java.util.Arrays.binarySearch() 方法用于搜索并返回给定字符数组范围内搜索关键字的索引。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建一个char数组
    char Arr[] = {'z', 'a', 'p', 'n', 'q', 'w', 'x'};

    //对指定范围的char数组进行排序,
    //指定范围或整个数组必须是
    //使用二分查找之前排序
    Arrays.sort(Arr, 2, 7);

    //打印排序后的数组
    System.out.println("After sorting the specified range"); 
    System.out.print("Arr contains:"); 
    for(char c: Arr)
      System.out.print(" " + c);

    //返回搜索到的key的索引号
    char val = 'x';
    int idx = Arrays.binarySearch(Arr, 2, 7, val);
    System.out.print("\nThe index number of 'x' is: " + idx);  
  }
}

上述代码的输出将是:

After sorting the specified range
Arr contains: z a n p q w x
The index number of 'x' is: 6