[英]Java recursive binary search throwing out of bounds exception?
嘿,有人要求我为大学的数据结构课写一个递归二进制搜索,但是我有一个小问题。 当我搜索超出范围的数字(在这种情况下超过10)时,将抛出超出范围的异常。 我知道为什么这样做,因为数组没有> 10个空格,但是我不知道如何解决它。 有任何想法吗?
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
}
附注:不要太夸张,但我也建议使用一致的缩进。 相信我,它在编写无错误程序方面大有帮助。
我想它以min = 0
和max = 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!
因此,如果您在两个方向中的任何一个方向上遍历数组,那么都不会找到请求的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.