java - 默认 java util 二进制搜索返回错误结果

标签 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

最佳答案

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

相关文章:

java - 如何在 Entry 类上调用 binarySearch() ?

java - 嵌套 GridBagLayout - 如何将子级的列与父级的列对齐

java - jHipster应用程序启动后执行方法

c++ - 多维数组迭代效率

arrays - 数据转换警告: A column-vector y was passed when a 1d array was expected

c# - 二元搜索和indexof 哪个更快?

algorithm - 如何在 O(n) 时间内对单链表进行二分查找?

java - 在 JFrame 和 JPanel 之间添加空间

java - Mobile - Codename - 怎么比母语快?

php - 如何在 PHP 中有效地搜索子数组?