Arrays.binarySearch() returns 错误的插入点

Arrays.binarySearch() returns wrong insertion point

这是代码:

public class Main {

    public static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {

        int arr[] = {10,50,999,1000};
        int index = Arrays.binarySearch(arr,55);
        System.out.println(index);
    }
}

这里输出的是'-3',如果这个公式输出"(-(insertion point) - 1)"表示插入点是'4'那是不对的

所以我缺少什么?

插入点是2,不是4

根据 official documentation:

The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key [...]

你的索引数组是

[10, 50, 999, 1000]
  0   1    2     3

第一个大于 55 的元素是索引 2 处的 999。请记住,索引从 0.

开始计数

所以插入点是2。对于公式 (-(insertion point) - 1),return 值必须是:

(-(2) - 1) = -3

这正是您得到的。

没有遗漏。Array.binarySearchs返回搜索关键字的索引,如果它包含在数组中;否则,(-(插入点) – 1)。插入点定义为将键插入数组的点:大于键的第一个元素的索引,或者 a.length 如果数组中的所有元素都小于指定的键。请注意,这保证 return 值将 >= 0 当且仅当找到密钥时。 此描述来自 here.