2.4.19实现MaxPQ的一个构造函数,接受一个数组作为参数。使用正文2.4.5.1节中所述的自底向上的方法构造堆。
public class E2d4d19<Key extends Comparable<Key>>
{
private Key[] pq;
private int N=0;
public E2d4d19(int maxN)
{ pq=(Key[]) new Comparable[maxN+1];}
public E2d4d19(Key[] a)
{
N=a.length;
pq=(Key[]) new Comparable[N+1];
for (int i=0;i<N;i++)
pq[i+1]=a[i];
for (int k=N/2;k>=1;k--)
sink(k);
}
public boolean isEmpty()
{ return N==0;}
public int size()
{ return N;}
public void Insert(Key v)
{
pq[++N]=v;
swim(N);
}
public Key delMax()
{
Key max=pq[1];
exch(1,N--);
pq[N+1]=null;
sink(1);
return max;
}
private void swim(int k)
{
while(k>1 && less(k/2,k))
{
exch(k/2,k);
k=k/2;
}
}//end swim
private void sink(int k)
{
while (2*k<=N)
{
int j=2*k;
if(j<N && less(j,j+1)) j++;
if(!less(k,j)) break;
exch(k,j);
k=j;
}
}//end sink
private boolean less(int i,int j)
{ return pq[i].compareTo(pq[j])<0;}
private void exch(int i,int j)
{
Key tmp=pq[i];
pq[i]=pq[j];
pq[j]=tmp;
}
public void show()
{
for(int i=1;i<=N;i++)
StdOut.printf("%s ",pq[i]);
StdOut.println();
}
public static void main(String[] args)
{
Integer[] a={1,5,7,2,4,3,6};
E2d4d19 pq=new E2d4d19(a);
StdOut.println(a.length+" "+pq.size());
while(!pq.isEmpty())
StdOut.println(pq.delMax());
}
}