java Arrays.binarySearch fails to find target

百般思念 提交于 2019-11-26 17:24:17

问题


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?


回答1:


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");  



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3674173/java-arrays-binarysearch-fails-to-find-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!