【发布时间】:2013-01-28 03:48:34
【问题描述】:
嘿,我将this C# code 转换为 c++ 为
void bubbleSort(int *inputArray, int passStartIndex, int currentIndex,int length)
{
if(passStartIndex == length - 1) return;
if(currentIndex == length - 1) return bubbleSort(inputArray, passStartIndex+1, passStartIndex+1,length);
//compare items at current index and current index + 1 and swap if required
int nextIndex = currentIndex + 1;
if(inputArray[currentIndex]>inputArray[nextIndex])
{
int temp = inputArray[nextIndex];
inputArray[nextIndex] = inputArray[currentIndex];
inputArray[currentIndex] = temp;
}
return bubbleSort(inputArray, passStartIndex, currentIndex + 1,length);
}
但是当我在长度为 50100 的输入数组上执行它时,它显示了我的异常
System.StackOverflowException 未处理 消息:未处理 在 example.exe 中发生“System.StackOverflowException”类型的异常
我做错了什么?如何解决?
【问题讨论】:
-
我也看到了@Benoit 发现的错误,但我仍然不明白为什么递归没有终止。
passStartIndex的测试似乎相当可靠。顺便说一句,我在我的 Linux 机器上运行这段代码时遇到了分段错误,而不是堆栈溢出,尽管这可能意味着同样的事情。但是,当长度为 510 而不是 50100 时,失败发生在我身上。我认为堆栈正在以某种方式被破坏,而不是无限递归。不幸的是,我没有更多的时间来做这件事了。祝你好运。
标签: c++ visual-c++ recursion stack-overflow bubble-sort