java - 堆排序 StackOverflow 错误

标签 java stack-overflow heapsort

我在标有 ** 的行反复收到 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/

相关文章:

java - 返回声明

java - 为什么我的数组中的索引 0 出现 stackoverflow 错误

c++ - ret地址指向无处(?)

c++ - 为什么编译器报告 "operator<< and operator>> recursive on all control paths will cause stack overflow "?

c - 在将其转换为排序数组时找到堆化数组,交换总数是最大可能的

java - XSS 漏洞 <c :out> tags in JSP pages

java - Tomcat 7 getting SSLv2Hello is disabled error when trying to make client server ssl authentication

java - 无法为可滑动的标签滑动

java - 使用节点的键创建一个数组

c - 堆排序 "visual"树打印额外的零