Arrays.binarySearch()返回错误的插入点。

huangapple go评论76阅读模式
英文:

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”,根据这个公式的输出:“(-(插入点) - 1)”,这意味着插入点是“4”,但这是不正确的。

那么我错过了什么?

英文:

This is the code:

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);
    }
}

The output here is '-3', if the output from this formula "(-(insertion point) - 1)" that means the insertion point is '4' and that is not right.

So what i am missing?

答案1

得分: 2

插入点是2,而不是4

根据官方文档

> 插入点被定义为将键插入数组的位置:第一个大于键的元素的索引[...]

您的带索引的数组是

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

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

所以插入点是2。使用公式(-(插入点) - 1),因此返回值必须是:

(-(2) - 1) = -3

这正是您得到的结果。

英文:

The insertion point is 2, not 4.

According to the 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 [...]

Your array with indices is

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

The first element greater than 55 is 999 at index 2. Remember that indices start counting at 0.

So the insertion point is 2. With the formula (-(insertion point) - 1) the return value must thus be:

(-(2) - 1) = -3

Which is exactly what you got.

答案2

得分: 0

以下是翻译好的内容:

没有缺失。Array.binarySearchs 返回搜索键的索引,如果它包含在数组中;否则为 (-(插入点) – 1)。插入点被定义为键将被插入到数组中的位置:第一个大于键的元素的索引,或者如果数组中的所有元素都小于指定的键,则为 a.length。请注意,这保证了只有当找到键时,返回值才会 >= 0。
这个描述来自这里

英文:

There is no missing.Array.binarySearchs Returned index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). 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, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
this describtion is from here.

huangapple
  • 本文由 发表于 2020年4月4日 16:58:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61025839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定