为什么这个递归函数抛出 StackOverFlow 错误???这是我的二进制搜索逻辑,它的确切错误点在哪里
Why this recursive function is throwing StackOverFlow error???this is my logic for binary search and Where is the exact point of error in it
这是我的二进制搜索逻辑,当我尝试 运行 它给出了
我的 Whosebug 错误....我也写了基本条件。它的确切错误点在哪里。
对于这段代码,我采用了具有预定义值的全局数组,并最初给出了 startingIndex=0 和 lastIndex=intArray.length-1;
public static void binarySearchInteger(int searchingElement,int
startingIndex,int lastIndex) {
middleIndex=(startingIndex+lastIndex)/2;
if(searchingElement==intArray[middleIndex])
System.out.println("Found the Element");
else if(startingIndex==lastIndex&&
searchingElement!=intArray[middleIndex])
System.out.println("There is no such Element");
else {
if(intArray[middleIndex]>searchingElement)
binarySearchInteger(searchingElement,
startingIndex,middleIndex);
else
binarySearchInteger(searchingElement,middleIndex,lastIndex);
}
}
假设startIndex == 0
和endIndex == 1
,则middleIndex
设置为1 / 2 == 0
(整数除法)。现在 startIndex == middleIndex
,因此您最后一次递归调用将使用具有完全相同参数值的方法并导致无限递归,这将导致堆栈溢出。
由于你已经在与中间元素进行比较,你不需要在递归搜索中包括中间元素,所以将最后一个递归调用替换为:
binarySearchInteger(searchingElement,middleIndex + 1,lastIndex);
你的代码中可能还有更多的错误,但是这个我是看了一下才发现的。您可以通过使用调试器并单步执行代码,准确查看发生的情况,自行发现错误。
这是我的二进制搜索逻辑,当我尝试 运行 它给出了 我的 Whosebug 错误....我也写了基本条件。它的确切错误点在哪里。 对于这段代码,我采用了具有预定义值的全局数组,并最初给出了 startingIndex=0 和 lastIndex=intArray.length-1;
public static void binarySearchInteger(int searchingElement,int
startingIndex,int lastIndex) {
middleIndex=(startingIndex+lastIndex)/2;
if(searchingElement==intArray[middleIndex])
System.out.println("Found the Element");
else if(startingIndex==lastIndex&&
searchingElement!=intArray[middleIndex])
System.out.println("There is no such Element");
else {
if(intArray[middleIndex]>searchingElement)
binarySearchInteger(searchingElement,
startingIndex,middleIndex);
else
binarySearchInteger(searchingElement,middleIndex,lastIndex);
}
}
假设startIndex == 0
和endIndex == 1
,则middleIndex
设置为1 / 2 == 0
(整数除法)。现在 startIndex == middleIndex
,因此您最后一次递归调用将使用具有完全相同参数值的方法并导致无限递归,这将导致堆栈溢出。
由于你已经在与中间元素进行比较,你不需要在递归搜索中包括中间元素,所以将最后一个递归调用替换为:
binarySearchInteger(searchingElement,middleIndex + 1,lastIndex);
你的代码中可能还有更多的错误,但是这个我是看了一下才发现的。您可以通过使用调试器并单步执行代码,准确查看发生的情况,自行发现错误。