递归二进制搜索代码中的StackOverflow错误

时间:2015-04-19 02:56:10

标签: java search

我已经为#34; Recursive Binary Search"编写了这段代码。我在标记的行上得到StackOverflowError。但是,我没有使用(l+h)/2作为mid,这可能导致堆栈溢出为大值。

public class RecursiveMethod
{
    public static int RecursiveBinarySearch(int[] array, int l, int h, int x)
    {
        l = 0;
        h = array.length - 1;

        while (l<=h)
        {
            int mid = l + (h-l)/2;

            if (x == array[mid])
                return mid;
            else if (x < array[mid])
                return RecursiveBinarySearch(array, l, mid-1, x); // overflow here
            else // last possibility: x > array[mid]
                return RecursiveBinarySearch(array, mid+1, h, x);
        }
        return -1;
    }

    public static void main (String[] args)
    {
        int[] a =
                  {2, 8, 12, 14, 16, 19, 24, 28, 31, 33,    // 0 - 9
                   39, 40, 45, 49, 51, 53, 54, 56, 57, 60,  // 10-19
                   63, 69, 77, 82, 88, 89, 94, 96, 97};     // 20-28

        for (int i = 0; i < a.length; i++)
            System.out.print("(" + a + "," + a[i] + ")" + "  ");

        System.out.println();
        System.out.print(RecursiveBinarySearch(a, 0, a.length, 1) + " ");
        System.out.print(RecursiveBinarySearch(a, 0, a.length, 26) + " ");
        System.out.print(RecursiveBinarySearch(a, 0, a.length, 85) + " ");
        System.out.print(RecursiveBinarySearch(a, 0, a.length, 99) + " ");
        System.out.println();
    }    
}

2 个答案:

答案 0 :(得分:0)

您始终设置lh并忽略args。因此,当你递归时,你再次从中间开始:

public static int RecursiveBinarySearch(int[] array, int l, int h, int x) {
  l = 0;
  h = array.length -1;

答案 1 :(得分:0)

我不明白为什么你在递归函数中使用while循环。您应该按照以下方式更改代码,它应该可以正常工作。

public class RecursiveMethod {
    public static int RecursiveBinarySearch(int[] array, int l, int h, int x) {
        if (h>=l)
            int mid = l + (h-l)/2;

        if (x == array[mid])
            return mid;
        else if ( l == h)
            return -1;
        else if (x < array[mid])
            return RecursiveBinarySearch(array, l, mid-1, x);
        if (x > array[mid])   // last possibility: x > array[mid]
            return RecursiveBinarySearch(array, mid+1, h, x);
    }
}

EDIT 正如Brett Okken指出的那样,你不应该在电话中覆盖你的l。,