我正在研究最大堆。我能够添加信息,但当我删除最大的东西出错。它用13#切换数字。不知道为什么。有人可以查看我的代码并找到它不工作的地方吗?
打印:Heap 55 46 23 13 45 22 17 13 16 1 12
何时打印:Heap = 55 46 23 44 45 22 17 13 16 1 12
谢谢!
private int current; //Current number of nodes in heap
private int[]cu; //Array to hold heap
public static final int maxSize =20;
public Heap ()
{
cu= new int[maxSize];
current = length();
}
private int length()
{
for(int i=1; i<maxSize;i++)
{
if(cu[i]!=0)
current++;
}
return current;
}
public boolean isEmpty()
{
return (current ==1);
}
public boolean isFull()
{
return (current == maxSize);
}
public boolean add(Comparable newNode)
{
if(isFull())
return false;
current++;
int t = current;
int to;
while(t>1)
{
to =t/2;
if((int)newNode <= cu[to])
break;
else
cu[t] = cu[to];
t =to;
}
cu[t]= (int) newNode;
return true;
}
public Comparable remove()
{
if(isEmpty())
return false;
int t= 1;
int to=2;
while(t<=current)
{
if((t<current)&& (cu[t]<=cu[t+1]))
t++;
if(cu[t]<= cu[current])
break;
to=t;
t*=2;
cu[to] = cu[t];
}
if (current>1)
cu[to] = cu[current];
current--;
return true;
}
public void print()
{
System.out.print("\nHeap = ");
for (int i = 1; i <= current; i++)
System.out.print(cu[i] +" ");
System.out.println();
}
public static void main(String a[])
{
Heap yay = new Heap();
yay.add(45);
yay.add(13);
yay.add(17);
yay.add(77);
yay.add(55);
yay.add(16);
yay.add(22);
yay.add(44);
yay.add(46);
yay.add(1);
yay.add(12);
yay.add(23);
yay.remove();
yay.remove();
System.out.println(yay.peekMax());
yay.print();
}
}