【问题标题】:Java binary search, high values throw exception [closed]Java二进制搜索,高值抛出异常[关闭]
【发布时间】:2013-06-06 16:28:53
【问题描述】:

在查看this 教科书页面上的示例后,我正在尝试实现递归二进制搜索。

我的算法在大多数情况下似乎都能正常工作,但在高于数组中最大值的值上,我得到一个ArrayIndexOutOfBoundsException。查看我的算法和教科书示例,它们似乎相同;有人可以帮我找出哪里出错了吗?

我知道这与this thread 中的问题基本相同,我已经考虑过它提出的解决方案。然而,示例代码并没有像这样实现任何参数更正,我想知道为什么没有它也能工作。

    public static int binarySearch(int[] array, int item, int lowPos, int highPos){
    if (lowPos > highPos){
        return -1;
    }

    int mid = (lowPos + highPos)/2;

    if (array[mid] == item){
        return mid;
    }else if (array[mid] > item){
        return binarySearch(array, item, lowPos, mid-1);
    }else{
        return binarySearch(array, item, mid+1, highPos);
    }
}

这是教科书的例子,显然不会产生错误:

    static int binarySearch(int[] A, int loIndex, int hiIndex, int value) {

   if (loIndex > hiIndex) {
         // The starting position comes after the final index,
         // so there are actually no elements in the specified
         // range.  The value does not occur in this empty list!
      return -1;
   }

   else {
         // Look at the middle position in the list.  If the
         // value occurs at that position, return that position.
         // Otherwise, search recursively in either the first
         // half or the second half of the list.
      int middle = (loIndex + hiIndex) / 2;
      if (value == A[middle])
         return middle;
      else if (value < A[middle])
         return binarySearch(A, loIndex, middle - 1, value);
      else   // value must be > A[middle]
         return binarySearch(A, middle + 1, hiIndex, value);
   }

} // end binarySearch()

【问题讨论】:

  • 你得到什么异常?你可以发布堆栈跟踪吗?
  • @LuiggiMendoza 他说他遇到了越界异常。
  • 无法复制该行为。您能否发布导致错误的代码(太懒了,也尝试通过它)?我在想你可能在那里提出了错误的论点。
  • 我唯一能得到的是你以错误的方式发送参数。请注意,book 方法使用数组、低索引、高索引和值,而您的方法使用数组、、低索引、高索引。这意味着,当从您的客户端类/方法调用 binarySearch 方法时,例如public static void main(String[] args).
  • OP,请你把我们的痛苦放出来,让我们知道谁是对的? ;)

标签: java search binary indexoutofboundsexception


【解决方案1】:

您的代码很好,您只是错误地传递了值。您可能使用了错误的 highPos 来启动您的方法,如果是这种情况,请使用 myArray.length -1 而不是 myArray.length。

否则,您对修改后的方法调用的参数完全错误,可能会切换值。调用代码应如下所示。

binarySearch(myArray, myIntToSearchFor, 0, myArray.length-1)

【讨论】:

  • 这很可能是问题所在。但是,由于我没有看到发布的调用代码(或者“您可能正在通过”),您是否正在透过魔法玻璃看?如果你是对的,那么随机猜测的荣誉。
  • 代码正确,所以排除过程
  • 我不这么认为。请参阅我对 OP 问题的最后评论。顺便说一句,我想知道您是如何消除以前从未见过的东西的:)。
  • 但是他正确地切换了他调用方法的方式来解决这个问题。所以这不是问题。代码不错,他的方法调用不行
  • 你是对的,这是另一种可能的解释,所以我修改了我的答案以反映这一点。但问题肯定是他如何调用方法,而不是方法代码本身。
【解决方案2】:

我相信您将 array.length 而不是 array.length - 1 作为参数传递给 highPos

【讨论】:

    猜你喜欢
    • 2011-04-30
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多