Java.util.Arrays 类

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

语法

public static <T> int  binarySearch(T[] a, int fromIndex, 
                                    int toIndex, T key, 
                                    Comparator<? super T> c)

这里,T 是数组中对象的类.

参数

a 指定要搜索的数组
fromIndex 指定要搜索的第一个元素(含)的索引。
toIndex 指定要搜索的最后一个元素(不包括)的索引。
key 指定要搜索的值。
c 指定比较器数组是有序的。 null 值表示应使用元素自然排序。

返回值

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

Exception

  • 如果范围包含使用指定比较器无法相互比较的元素,或者搜索键与搜索键不可比较,则抛出 ClassCastException使用此比较器的范围内的元素。
  • 如果 fromIndex > toIndex,则抛出 IllegalArgumentException
  • 如果 fromIndex < 0,则抛出 ArrayIndexOutOfBoundsException或 toIndex > a.length

示例:

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

import java.util.*;

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

    //使用比较器为null来排序
    //使用自然排序
    Comparator<Byte> comp = null;

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

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

    //返回搜索到的key的索引号
    Byte val = -10;
    int idx = Arrays.binarySearch(Arr, 2, 7, val, comp);
    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