二进制搜索java数组。binarySearch无法找到目标
String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};
// Search for the word "cat"
int index = Arrays.binarySearch(sortedArray, "Quality");
我总是得到-3
。问题出在"Name"
。为什么我的数组中不能有"Name"
?有什么想法吗
# 1 楼答案
必须对数组进行排序,才能进行二进制搜索。{a1}的javadoc说:
(重点加上。)
原因很简单。二进制搜索算法的前提是输入数组已排序
# 2 楼答案
要使用
binarySearch
,首先需要自己对数组进行排序:# 3 楼答案
必须对数组进行排序。从binarySearch()的Javadoc: