以下是课本上对二叉堆的叙述
二叉堆
结构性质:是一颗完全二叉树(最后一个节点的左边,上层都充满节点)
堆序性质:对于每一个节点X,X的父节点的关键字小于或等于X节点的关键字
二叉堆实际上是一个用数组储存的二叉树,但是数组下标为0的地方没有关键字
包括的操作:insert(),findMIn(),deleteMin(),isEmpty(),makeEmpty(),percolateDown(),buildHeap(),enlargeArray();
包括的元素:int len, T array[];
java中的实现时PriorityQueue
下面是我的实现,其中有的方法,和课本上略有不同:
import java.util.Arrays;
public class BinaryHeap {
private static int heap[],len;
public static void main(String[] args) {
// TODO 自动生成的方法存根
heap=new int[]{0,150,80,40,30,10,70,110,100,20,90,60,50,120,140,130};
len=heap.length-1;
buildHeap();
for(int i=0;i<heap.length;i++){
System.out.print(heap[i]+"\t");
}
// deleteMin();
delete(3);
// decreaseKey(15,130);
// insert(15);
System.out.println("");
for(int i=0;i<heap.length;i++){
System.out.print(heap[i]+"\t");
}
}
private static void enlargeArray(){
heap=Arrays.copyOf(heap, heap.length+heap.length<<1);
}
private static void insert(int x){
int i=0;
if(len>=heap.length-1){
enlargeArray();
}
heap[len+1]=x;
for(i=len+1;i>0&&(x<heap[i/2]);i/=2){
heap[i]=heap[i/2];
}
heap[i]=x;
len++;
}
private static int deleteMin(){
if(isEmpty()){
return 0;
}
int min=heap[1];
heap[1]=heap[len];
percolateDown(1);
len--;
return min;
}
private static void percolateDown(int pos){
int temp=heap[pos],child=0,i,last=0;
last=len>>1;
for(i=pos;i<=len;i=child){
child=2*i;
if(i<last){
if(heap[child]>heap[child+1]){
child++;
}
}else if(i>last){
break;
}else if(child<len){
if(heap[child]>heap[child+1]){
child++;
}
}
if(heap[child]>temp){
break;
}
heap[i]=heap[child];
}
heap[i]=temp;
}
private static boolean isEmpty(){
if(len==0){
return true;
}
return false;
}
private static void buildHeap(){
for(int i=len>>1;i>0;i--){
percolateDown(i);
}
}
private static int decreaseKey(int pos,int off){
int value=heap[pos]-off,i=0;
for(i=pos;i>>1>0&&value<heap[i>>1];i=i>>1){
heap[i]=heap[i>>1];
}
heap[i]=value;
return value;
}
private static void intcrearseKey(int pos,int off){
int value=heap[pos]+off;
heap[pos]=value;
percolateDown(pos);
}
private static int delete(int pos){
int value=decreaseKey(pos,heap[pos]);
deleteMin();
return value;
}
}