0

I have written the following program for maxifying a heap in 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);
        }
    }
}

I'm getting the same output as inp. I feel there is something wrong with me expecting the recursive method to change the inp ArrayList.

mbsingh
  • 499
  • 10
  • 26

1 Answers1

0

You're -always- recursively calling maxifyHeap, so its hitting a stack overflow, fix your recursive calls to not infinitely recurse.

Entropy
  • 64
  • 1
  • 4
  • Entropy, Thanks. Putting the recursive call inside that last if statement worked like this : if(largestIndex!=curIndex) { temp = inp.get(largestIndex); inp.set(largestIndex, inp.get(curIndex)); inp.set(curIndex, temp); maxifyHeap(inp, largestIndex); } But now the problem is that it's not maxifying the heap, i.e input & output are same :| I think there is something wrong with me expecting the inp ArrayList to change after I call the recursive method. Any inputs on how I can fix this? – mbsingh May 16 '14 at 04:29