如果我有一个看起来像这样的数组:
int[] arr = {6, 12, 3, 9, 8, 25, 10};
为什么返回-2:
Arrays.binarySearch(arr, 8);
据我了解,binarySearch仅在对数组排序时才有效.我的问题是什么决定返回的索引?
解决方法:
正如@assylias在评论中提到的,我可以引用binarySearch的文档
Returns:
index of the search key, if it is contained in the array within the specified range; 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 in the range greater than the key, or toIndex if all elements in the range 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.
因此,基本上,这就是您尝试搜索未排序数组时发生的情况:
{6、12、3、9、8、25、10}
>它采用中间元素9并将其与您搜索的元素8进行比较,因为8较低,因此它占下半部分{6,12,3}
>在第二步中,它将12与8相比较,并且由于8再次降低,因此花费了下半部分{6}
> 6不等于8,因为它是最后一个元素,所以没有找到您想要的东西
>它返回(-(插入点)-1),其中插入点为
the index of the first element in the range greater than the key
>在您的情况下,索引是1,因为第一个元素大于8是12,并且它的索引是1
>当您将其放入方程式时,它返回(-1-1)等于-2
希望我回答了你的问题.
标签:binary-search,arrays,java
来源: https://codeday.me/bug/20191110/2015068.html