Java.util.Arrays 类

java.util.Arrays.binarySearch()方法用于在指定数组的范围内搜索指定对象使用二分搜索算法。在进行此调用之前,必须根据其元素的自然顺序(如通过 sort(Object[], int, int) 方法)将范围按升序排序。如果未排序,则结果不确定。如果范围包含多个等于指定对象的元素,则不保证会找到哪一个。

语法

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

参数

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

返回值

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

Exception

  • 如果搜索键无法与指定范围内的数组元素进行比较,则抛出 ClassCastException
  • 如果 fromIndex > toIndex
  • ,则抛出 IllegalArgumentException
  • 如果 fromIndex < 0 或 toIndex > a.length,则抛出 ArrayIndexOutOfBoundsException

示例:

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

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建数组对象
    Object Arr[] = {10, 25, 5, -10, -30, 0, 100};

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

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

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

上述代码的输出将是:

After sorting the specified range
Arr contains: 10 25 -30 -10 0 5 100
The index number of -10 is: 3