java Arrays.binarySearch fails to find target

守給你的承諾、 提交于 2019-11-27 16:05:57

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

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.

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