java Arrays.binarySearch 找不到目标
String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};
// Search for the word "cat"
int index = Arrays.binarySearch(sortedArray, "Quality");
我总是得到-3
。问题出在“名称”
。为什么我的数组中不能有 "Name"
?有什么想法吗?
String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};
// Search for the word "cat"
int index = Arrays.binarySearch(sortedArray, "Quality");
I always get -3
. Problem is in "Name"
. Why I can not have "Name"
in my array? Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了使用
binarySearch
,您需要先自己对数组进行排序:In order to use
binarySearch
, you will need to sort the array yourself first:数组必须是有序的。来自binarySearch()的Javadoc:
The array is must be sorted. From Javadoc of binarySearch():
数组必须经过排序才能进行二分搜索。 binarySearch 说的是:
(强调。)
原因很简单。二分查找算法的前提条件是输入数组已排序。
An array must be sorted for binary search to work. The javadoc for binarySearch says this:
(Emphasis added.)
And the reason is simple. The binary search algorithm has a precondition that the input array is sorted.