我正在尝试使用 Arrays.binarySearch() 搜索 int 数组中的值,并且我知道如果值可以在数组中找到,则此方法返回值的索引号,如果数组没有找到include value 方法返回负数。
这是我的数组:
int[] searchInArray=new int[6];
searchInArray = new int[]{2,3,4,22,1,2};
这是我的代码:
int result1=Arrays.binarySearch(searchInArray,55);
int result2=Arrays.binarySearch(searchInArray, 22);
当我运行此代码时,我得到 return1=-7 和 return2=-7。
然后我尝试找到 1 而不是 22,然后 result2 为“-1”。
我哪里出错了?
最佳答案
使用binarySearch()
的前提是数组必须是有序的。你的不是。
引自the javadoc :
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
(强调我的)
关于java - 在 int 数组中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22271536/