【问题标题】:Java recursive binary search throwing out of bounds exception?Java递归二进制搜索抛出越界异常?
【发布时间】:2011-04-30 08:20:03
【问题描述】:

嘿,我被要求为我在大学的数据结构课程编写递归二进制搜索,但我遇到了一个小问题。当我搜索超出范围的数字(在这种情况下超过 10)时,它会引发超出范围的异常。我理解它为什么这样做,因为数组没有> 10个空格,但我不知道如何解决它。有任何想法吗?

我搜索的数组是有序数组 1 - 10(索引 0 - 9)。

 public int recursiveBinarySearch(int[] anArray, int searchedNumber, int min, int max) {

    if (min > max)
        {
                System.out.println(searchedNumber + " is not present in tha array.");
                //return -1 to show that the value has not been found
        return -1;
        }
        // find the centre of the array
        int centre = (min + max) / 2;

    if (anArray[centre] == searchedNumber)
        {
                System.out.println(searchedNumber + " was found at index " + centre);
        return centre;
        }

        if (anArray[centre] < searchedNumber)
        {
        return recursiveBinarySearch(anArray, searchedNumber, centre+1, max);
        }

        return recursiveBinarySearch(anArray, searchedNumber, min, centre-1);

 }

【问题讨论】:

  • 二分搜索不应该使用 / 2 它应该使用按位 >>.
  • 为什么?你不在乎这些比特长什么样。您关心数字是多少(以及它的一半是多少)。这种类型的优化应该留给编译器/jvm。

标签: java search recursion binary


【解决方案1】:
public int recursiveBinarySearch(...) {
    if (max >= array.length) {
        max = array.length - 1;
    }
    if (min < 0) {
        min = 0;
    }
    ... rest of the code
} 

PS 不要唠叨,但我也建议使用一致的缩进。相信我,它对编写无错误的程序很有帮助。

【讨论】:

  • 非常感谢,这正是我所需要的。至于缩进,感谢您指出,我的程序的其余部分是缩进的……只是由于某种原因不是这种方法。再次感谢。
【解决方案2】:

我想它以min = 0max = 9 开头,然后就可以了

min = 0, max = 9, c = (0+9 / 2) = 4
min = 5, max = 9, c = (6+9 / 2) = 7
min = 8, max = 9, c = (8+9 / 2) = 8
min = 9, max = 9, c = (9+9 / 2) = 9
min = 10, max = 9, ...

正如你所看到的,min = 10 当然会引起问题。为了避免这种情况,只需扩大初始条件:

if (min > max || min > Array.length -1 || max < 0)
  // not found!

因此,如果您从两个方向中的任何一个方向遍历数组,则将找不到请求的元素。

【讨论】:

  • 为什么会出问题?他在if (min &gt; max) 中负责处理
猜你喜欢
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 2018-11-19
  • 2013-03-30
  • 1970-01-01
相关资源
最近更新 更多