使用递归的二进制搜索仅采用参数中的搜索值

时间:2019-01-17 16:51:10

标签: java recursion

我实际上需要通过仅使用被参数化的构造函数中的搜索项来解决该问题。我该怎么做?我被该程序卡住了!

我可以用中间元素做得很好,但是当我尝试除中间元素之外的其他元素时,它显示了堆栈溢出错误。

public static int binary_search(int v)
{
    l=0;
    u=n-1;
    int mid = (l+u)/2;
    if(A[mid]==v)
        return 1;
    else if(v<A[mid])
    {
        binary_search(v);
        mid = mid-1;
    }
    else if(v>A[mid])
    {
        binary_search(v);
        mid = mid+1;
    }
    return -1;
}

与中间元素配合得很好,但是对于其他元素,没有解决方案。

1 个答案:

答案 0 :(得分:2)

您需要将更新的lu作为参数传递给递归方法。您正在做的是在每个调用中为l(= 0)和u(= n-1)分配相同的值。换句话说,每个递归调用都不能解决 smaller 问题。这是相同问题,因此会导致StackOverflow。

这是一个伪代码

int binarySearch(int v, int l, int u) {
    if (l <= u) {
       find mid
       is the element at mid:
           return 1;// Can be 'mid' to return the index at which it was found.
       should we go left:
           return binarySearch(v, l, mid - 1);
       should we go right:
           return binarySearch(v, mid + 1, u);
    } 
    return -1; //Not found
}

注意事项:

  1. 基本条件(l <= u)。这将使我们能够检测到缺少的元素条件并终止递归。
  2. 每个递归调用中的return关键字,否则,您将始终返回-1。

更新:

如果lu声明为静态,则需要在进行递归调用之前对其进行更新。

int binarySearch(int v) {
    if (l <= u) {
       find mid
       is the element at mid:
           return 1;// Can be 'mid' to return the index at which it was found.
       should we go left:
           u = mid - 1
           return binarySearch(v);
       should we go right: 
           l = mid + 1
           return binarySearch(v);
    } 
    return -1; //Not found
}

注意:调用此方法之前,您必须先设置l = 0u = n - 1

相关问题