我在标有 ** 的行反复收到 StackOverflow 错误。如果我尝试对 3 个以上的数字进行排序,堆栈会溢出,但适用于 3 个或更少的数组,因此我认为不存在无限递归。 有人可以向我解释为什么第 246 行似乎是堆栈溢出的根源吗?
谢谢
public static void heapSort(double [] a,int node, int index, boolean upcheck){
if(node < 0){
}
else if(node > a.length-index){
}
else if(upcheck){
if(!testHeap(a,node,(2*node)+1) || !testHeap(a,node,(2*node)+2) ){
int min = 0;
if(a[(2*node)+1] > a[(2*node)+2]){
min = (2*node)+2;
}
else{
min = (2*node)+1;
}
switchHeap(a,node,min);
****************************heapSort(a,(node-1)/2,index,true);*********************
}
}
else if(node == (a.length-index-1)/2){
if((2*node)+1 <= a.length-index){
if(testHeap(a,node,(2*node)+1)){
}
else{
heapSort(a,(node-1)/2,index,true);
}
if((2*node)+2 <= a.length-index){
if(testHeap(a,node,(2*node)+2)){
}
else{
heapSort(a,(node-1)/2,index,true);
}
}
}
switchHeap(a,0,a.length-index);
index++;
heapSort(a,0,index,false);
}
else{
if((2*node)+1 <= a.length-index){
if(testHeap(a,node,(2*node)+1)){
}
else{
heapSort(a,(node-1)/2,index,true);
}
heapSort(a,(2*node)+1,index,false);
if((2*node)+2 <= a.length-index){
if(testHeap(a,node,(2*node)+2)){
}
else{
heapSort(a,(node-1)/2,index,true);
}
heapSort(a,(2*node)+2,index,false);
}
}
}
}//heapSort - method
最佳答案
由于您在代码中进行递归调用,您将收到 StackOverFlowError
。即
static void heapSort(double [] a,int node, int index, boolean upcheck)
递归调用自身。当工作完成时,您需要在这种递归方法调用中使用 break;
根据文档,
公共(public)类StackOverflowError 扩展VirtualMachineError
由于应用程序递归太深而发生堆栈溢出时抛出。
请阅读此link了解有关该错误的更多信息。接受的答案说明了一切
关于java - 堆排序 StackOverflow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20899689/