default java util binary-search返回错误的结果

时间:2015-04-24 18:21:45

标签: java arrays binary-search

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

1 个答案:

答案 0 :(得分:4)

如果您阅读了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.
...