【问题标题】:Compile time error in Binary Search Recursive implementation二分搜索递归实现中的编译时错误
【发布时间】:2017-02-05 22:26:13
【问题描述】:

我在二分搜索递归实现中遇到一个编译错误

这是我的方法:

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 值,但我仍然收到错误为什么会发生这种情况。任何相关的想法都会受到赞赏。

谢谢

【问题讨论】:

  • 究竟是什么错误,发生在哪里?

标签: java recursion data-structures binary-search


【解决方案1】:

如果start > enda[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
    }

}

【讨论】:

  • 从字面上看,堆栈溢出对你们来说是一个更好的地方
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
相关资源
最近更新 更多