在java中最大化堆 - Stack Overflow错误

时间:2014-05-16 04:21:58

标签: java runtime-error heap stack-overflow max-heap

我编写了以下用于在Java中最大化堆的程序。


package heap;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class HeapMaxify 
{
    public static void main(String[] s)
    {
        List<Integer> inp = new ArrayList<Integer>();
        Scanner inpObj = new Scanner(System.in);
        inp.add(inpObj.nextInt());
        for(int i=1;i<=inp.get(0);i++)
            inp.add(inpObj.nextInt());
        System.out.println("Current heap follows :");
        int elemInLine = 1;
        int count = 0;
        for(int i=1;i<=inp.get(0);i++)
        {
            System.out.print(inp.get(i)+"\t");
            count++;
            if(count==elemInLine)
            {
                System.out.println();
                count = 0;
                elemInLine *= 2;
            }
        }
        maxifyHeap(inp,1);
        System.out.println("Maxified heap follows :");
        elemInLine = 1;
        count = 0;
        for(int i=1;i<=inp.get(0);i++)
        {
            System.out.print(inp.get(i)+"\t");
            count++;
            if(count==elemInLine)
            {
                System.out.println();
                count = 0;
                elemInLine *= 2;
            }
        }
    }
    private static void maxifyHeap(List<Integer> inp, int curIndex)
    {
        int leftIndex = 2*curIndex;
        int rightIndex = (2*curIndex)+1;
        int largestIndex=0;
        int temp;
        if(leftIndex<=inp.get(0)&&inp.get(leftIndex)>inp.get(curIndex))
            largestIndex = leftIndex;
        else
            largestIndex = curIndex;
        if(rightIndex<=inp.get(0)&&inp.get(rightIndex)>inp.get(largestIndex))
            largestIndex = rightIndex;
        if(largestIndex!=curIndex)
        {
            temp = inp.get(largestIndex);
            inp.set(largestIndex, inp.get(curIndex));
            inp.set(curIndex, temp);
                    maxifyHeap(inp, largestIndex);
        }
    }
}

我获得与inp相同的输出。 我觉得我希望递归方法改变inp ArrayList会有问题。

1 个答案:

答案 0 :(得分:0)

你总是以递归方式调用maxifyHeap,因此它会遇到堆栈溢出,修复你的递归调用而不是无限递归。