我需要打印一个存储为数组的堆。我创建了一个类来执行此操作。但是,当我运行程序时,它只运行main方法的前半部分。这是主要方法:
public static void main(String args[])
{
Random r = new Random();
int newNum;
Heap heap = new Heap(21);
//Creates a heap of 20 random integers
for(int i = 1; i <= 20; i++)
{
newNum = r.nextInt(1000);
heap.add(newNum);
}
System.out.println("Completed Heap:");
heap.print(1, 0);
//Removes the max of the Heap and prints each new iteration
for(int j = 20; j >= 1; j--)
{
System.out.println("\nRemoved " + heap.removeMax() + " from Heap:");
heap.print(1, 0);
}
}
它打印出已完成的堆,但是应该在删除max之后打印堆,直到完全删除堆。然而,它打印完成的,然后似乎卡住了。有什么想法/建议吗?
编辑:我的堆类的打印方法:
public void print(int start, int level)
{
System.out.println("");
int left = start * 2, right = left + 1;
if(right <= heap.length - 1)
{
print(right, level + 1);
}
if(heap[start] == 0)
{
return;
}
else
{
for(int i = 0; i <= level; i++)
{
System.out.print(" ");
}
System.out.print(heap[start]);
}
if(left <= heap.length - 1)
{
print(left, level + 1);
}
}