java 排序返回索引_java-如果未对数组进行排序,则binarySearch返回一个随机索引;否则为false.返回的索引背后的逻辑是什么?...

如果我有一个看起来像这样的数组:

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值