开发者

java Arrays.binarySearch fails to find target

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?


In order to use binarySearch, you will need to sort the array yourself first:

String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   

java.util.Arrays.sort(sortedArray);

int index = Arrays.binarySearch(sortedArray, "Quality");  


The array is must be sorted. From Javadoc of binarySearch():

The range must be sorted into ascending order according to the natural ordering of its elements prior to making this call. If it is not sorted, the results are undefined.


An array must be sorted for binary search to work. The javadoc for binarySearch says this:

The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call. If it is not sorted, the results are undefined.

(Emphasis added.)

And the reason is simple. The binary search algorithm has a precondition that the input array is sorted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜