我很想知道当我使用 Arrays.binarySearch 而不进行排序时得到的答案背后的逻辑是什么。
int d[]={6,-4,12,0,-10};
int x=12;
int y=Arrays.binarySearch(d,x);
System.out.println(y);
输出:2
我正在准备一个java竞赛,其中会出现这种罕见的情况,所以我问了这个问题。请帮助提供任何可能的解决方案。
最佳答案
你很幸运。 Java 实现要求对数组进行排序以保证正确的答案:
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.
关于java - Arrays.binarySearch() 如何在不排序的情况下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19756565/