default java util binary-search returns 错误的结果

default java util binary-search returns wrong results

我在 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.
...