我从 java util 中的二分搜索得到了非常奇怪的行为
这段代码
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] A={-1, 6, 3, 4, 7, 4} ;
for(int i=0;i<A.length;i++)
{
System.out.println(Arrays.binarySearch(A,A[i])+"========="+A[i]);
}
}
应该显示数组中每个元素的所有值及其索引
但它适用于除第二个元素之外的所有元素
返回值是
0=========-1
-5=========6
2=========3
3=========4
4=========7
3=========4
我在 java 7 和 java 8 上测试了它,它给了我相同的结果
您可以在线测试 https://ideone.com/7wMFgG
最佳答案
如果您阅读了binarySearch 的Javadoc,您会发现数组必须已排序:
/**
* Searches the specified array of longs for the specified value using the
* binary search algorithm. The array must be sorted (as
* by the {@link #sort(int[])} method) prior to making this call. If it
* is not sorted, the results are undefined.
...
关于java - 默认 java util 二进制搜索返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29854798/