【发布时间】: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