我在二分搜索递归实现中遇到一个编译错误
这是我的方法:
public static int binarySearch(int[] a, int start, int end, int x) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] > x) {
binarySearch(a, start, mid - 1, x);
} else {
binarySearch(a, mid + 1, end, x);
}
}
我为此给出了两个基本情况并返回两个 int 值,但我仍然收到错误,为什么会发生这种情况。任何相关的想法将不胜感激。
谢谢
最佳答案
如果 start > end
和 a[mid] == x
都为 false
,您认为第一次调用会返回什么?
您还需要返回递归调用,以便找到的值(或 -1
)将通过递归堆栈帧传播回来:
public static int binarySearch(int[] a, int start, int end, int x) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] > x) {
return binarySearch(a, start, mid - 1, x); // return here
} else {
return binarySearch(a, mid + 1, end, x); // return here
}
}
关于java - 二分查找递归实现中的编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39739052/