二进制搜索排序数组中不存在的数字,返回大于-1的负数 [英] Binary Search a non-existing number in a sorted array, return a larger negative number than -1
本文介绍了二进制搜索排序数组中不存在的数字,返回大于-1的负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
搜索数为12时,为什么返回-6而不是-1?
When the search number is 12, why does it return -6 instead of -1?
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("1. Index is " + Arrays.binarySearch(list, 11));
System.out.println("2. Index is " + Arrays.binarySearch(list, 12));
Result:
1. Index is 4
2. Index is -6
更新
现在我明白了,因为Arrays.binarySearch将返回
Update
Now I understand because Arrays.binarySearch will return
(-(insertion point) - 1)
如果数字不在数组中.IE12在插入5时返回(-(5)-1)= -6.感谢您的帮助.
if the number is not in the array. i.e 12 is at insertion of 5, so return (-(5) - 1) = -6. Thanks for the help.
推荐答案
You may refer to the Javadoc : Arrays.binarySearch(int[] a,int key)
它返回:
- 搜索键的
-
索引
(如果包含在数组中); - 否则:(
-(插入点)-1
).
index of the search key
, if it is contained in the array;- otherwise : (
-(insertion point) - 1
).
在这里插入点将是:
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
// 1^ 2^ 3^ 4^ 5^
位置 5
,所以(-5-1)= -6
这篇关于二进制搜索排序数组中不存在的数字,返回大于-1的负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文