【问题标题】:Searching in int arrays在 int 数组中搜索
【发布时间】:2014-03-09 00:10:37
【问题描述】:

我正在尝试使用Arrays.binarySearch() 在 int 数组中搜索值,并且我知道如果值会在数组中找到,则此方法返回值的索引号,如果数组不包含值,则方法返回负数。

这是我的数组:

int[] searchInArray=new int[6];
searchInArray = new int[]{2,3,4,22,1,2};

这是我的代码:

int result1=Arrays.binarySearch(searchInArray,55);
int result2=Arrays.binarySearch(searchInArray, 22);

当我运行此代码时,我得到 return1=-7 和 return2=-7。

然后我尝试找到 1 而不是 22 然后结果 2 为“-1”。

我在哪里犯错了?

【问题讨论】:

  • 嗯,你期待什么?

标签: java arrays binary-search


【解决方案1】:

使用binarySearch()的前提是数组必须是有序的。你的不是。

引用the javadoc:

使用二进制搜索算法在指定的整数数组中搜索指定的值。 在进行此调用之前,必须对数组进行排序(如通过 sort(int[]) 方法)。如果未排序,则结果未定义。 如果数组包含多个具有指定值的元素,则无法保证会找到哪一个。

(强调我的)

【讨论】:

    【解决方案2】:

    在尝试使用二进制搜索之前,您需要确保数组已排序。以下代码应该可以按预期工作:

        int[] searchInArray = new int[6];
        searchInArray = new int[] { 2, 3, 4, 22, 1, 2 };
    
        Arrays.sort(searchInArray);
        final int result1 = Arrays.binarySearch(searchInArray, 55);
        final int result2 = Arrays.binarySearch(searchInArray, 22);
    
        System.out.println("result1 " + result1);
        System.out.println("result2 " + result2);
    

    您也不应该期望返回 -1。 Arrays.binarySearch 返回一个负数来指示值应该插入的位置。来自javadoc

    搜索键的索引,如果它包含在数组中;否则,(-(插入点)- 1)。插入点定义为键将插入数组的点:第一个元素的索引大于键,或者如果数组中的所有元素都小于指定的键,则为 a.length。请注意,这保证了当且仅当找到键时返回值将 >= 0。

    【讨论】:

      猜你喜欢
      • 2017-04-16
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 2013-04-15
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多