简体   繁体   English

Java递归二进制搜索抛出界外异常?

[英]Java recursive binary search throwing out of bounds exception?

Hey, I have been asked to write a recursive binary search for my data structure class in university, but i'm having a slight problem. 嘿,有人要求我为大学的数据结构课写一个递归二进制搜索,但是我有一个小问题。 When i search for a number that is out of bounds (over 10 in this case) it throws an out of bounds exception. 当我搜索超出范围的数字(在这种情况下超过10)时,将抛出超出范围的异常。 I understand why it's doing it, due to the array not having >10 spaces, but i don't know how to work around it. 我知道为什么这样做,因为数组没有> 10个空格,但是我不知道如何解决它。 Any ideas? 有任何想法吗?

The array that im searching is an ordered array 1 - 10 (index 0 - 9). im搜索的数组是有序数组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);

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

PS Not to be a nagger, but I would also recommend using consistent indentation. 附注:不要太夸张,但我也建议使用一致的缩进。 Believe me, it helps greatly in writing bug-free programs. 相信我,它在编写无错误程序方面大有帮助。

I suppose it starts with min = 0 and max = 9 , then it goes 我想它以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, ...

As you can see it gets over the bound, min = 10 will of course cause problems. 如您所见, min = 10当然会引起问题。 To avoid that just widen the initial condition: 为了避免这种情况,请扩大初始条件:

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

so that if your going over the array in any of two directions then the requested element won't be found. 因此,如果您在两个方向中的任何一个方向上遍历数组,那么都不会找到请求的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM