Java递归二进制搜索抛出超出范围的异常?

时间:2010-10-25 17:15:59

标签: java search recursion binary

嘿,我被要求在大学里为我的数据结构课写一个递归二进制搜索,但是我遇到了一个小问题。当我搜索一个超出范围的数字(在这种情况下超过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 个答案:

答案 0 :(得分:1)

public int recursiveBinarySearch(...) {
    if (max >= array.length) {
        max = array.length - 1;
    }
    if (min < 0) {
        min = 0;
    }
    ... rest of the code
} 

PS不是匕首,但我也建议使用一致的缩进。相信我,它有助于编写无bug程序。

答案 1 :(得分:0)

我认为它从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!

这样如果你在两个方向中的任何一个方向上遍历数组,那么将找不到所请求的元素。