[英]StackOverflow Error in Recursive Binary Search Code
我已經為“遞歸二進制搜索”編寫了此代碼。 我在標記的行得到了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();
}
}
您始終設置l
和h
並忽略args。 因此,當您遞歸時,您又從精確的中間開始:
public static int RecursiveBinarySearch(int[] array, int l, int h, int x) {
l = 0;
h = array.length -1;
我不明白為什么在遞歸函數中使用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);
}
}
編輯正如布雷特·奧克肯(Brett Okken)所指出的那樣,您不應在通話中覆蓋您的l,h。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.