Introduction:usually,we tend to insert a new value into a container and get a min or max value from the container,if the input frequency and the output frequency are about the same ,then we may construct a contanier with average less operation time.we can use the heap structure,it's a compelete binary tree.
so firstly we may see the usual operation:
constructed function:
public IntMinPQ(){elements=new Integer[1];elements[0]=Integer.MAX_VALUE;}
public IntMinPQ(int max){maxSize=max+1;elements=new Integer[maxSize];elements[0]=Integer.MAX_VALUE;}
public IntMinPQ(Integer[]a){
int len=a.length;
maxSize=len+1;
elements=new Integer[maxSize];
elements[0]=Integer.MAX_VALUE;
for(int i=0;i<len;++i){
insert(a[i]);
}
}
then the often used functions:
public void insert(Integer v){
if(size<maxSize){
elements[++size]=v;
}
swimUpdate(size);
}
public Integer min(){return elements[1];}
public Integer delMin(){
Integer temp=elements[1];
percolateDown();
return temp;
}
public boolean isEmpty(){return size==0;}
public int size(){return size;}
In the above functions there are some assistant fucntions:
In order to get a value from the container with O(log(N)) time , we need a insert fucntion to keep the insert time:
private void swim(int k){
while(k>1){
if(less(k,k/2)){
swap(k,k/2);
}else{
break;
}
k/=2;
}
}
also we need a function to keep the get time with O(log(N)) time:
private void percolateDown(){
int index=1;
while(2*index<size){
if(less(2*index,2*index+1)){
elements[index]=elements[2*index];
index=2*index;
}else{
elements[index]=elements[2*index+1];
index=2*index+1;
}
}
elements[index]=elements[size];
elements[size]=null;
--size;
}
the problem is how to handle with the last element,the function given above is called
percolateDown(),just as its name implies:the element with less value is jump down step by step.
besides that ,some inner variables are also needed:
private Integer[] elements=null;
private int size=0;
private int maxSize=0;
The end.