目录
最大优先队列的实现
package DataStructure.priority;
//最大优先队列
//用大顶堆去实现
public class MaxPriorityQueue<T extends Comparable<T>> {
private T[] items;
private int N;
public MaxPriorityQueue(int capacity){
this.items=(T[])new Comparable[capacity+1];
this.N=0;
}
public int size(){
return N;
}
public boolean isempty(){
return N==0;
}
public boolean less(int i,int j){
return items[i].compareTo(items[j])<0;
}
public void exch(int i,int j){
T tmp=items[i];
items[i]=items[j];
items[j]=tmp;
}
public void insert(T t){
items[++N]=t;
swim(N);
}
public T delMax(){
T max=items[1];
exch(1,N);
N--;
sink(1);
return max;
}
//上浮算法
public void swim(int k){
while(k>1){
if(less(k/2,k)){//如果父节点小于k则交换
exch(k/2,k);
}
k=k/2;
}
}
//下沉算法
public void sink(int k){
while(2*k<=N){//有左子节点
int max;
if(2*k+1<=N){//有右子节点
if(less(2*k,2*k+1)){
max=2*k+1;
}else{
max=2*k;
}
}else{
max=2*k;
}
if(!less(k,max)){
break;
}
exch(k,max);
k=max;
}
}
}
测试类及结果