二叉堆的实现代码

因为二叉堆满足完全二叉树,一颗高为h的完全二叉树有2^h到2^h-1个节点,那么就可以用数组来表示。




public
class HeapDemo<T extends Comparable<? super T>>{ public HeapDemo(){ this(DEFAULT_CAPACITY); } public HeapDemo(int capacity){ makeEmpty(); enlargeArray(capacity); } public HeapDemo(T[] items){ currentSize=items.length; array=(T[]) new Comparable[(currentSize+2)*11/10]; int i=0; for (T t : items) { array[i++]=t; } buildHeap(); } public void insert(T val){ if(currentSize==array.length-1){ enlargeArray(2*array.length-1); } int hole=++currentSize; for(array[0]=val;val.compareTo(array[hole/2])<0;hole/=2){ array[hole]=array[hole/2]; } array[hole]=val; } public T findMin(){ return array[1]; } public T deleteMin() { if(isEmpty()){ throw new RuntimeException("堆为空"); } T minnum=findMin(); array[1]=array[currentSize--]; percolateDown(1); return minnum; } public boolean isEmpty(){ return currentSize==0; } public void makeEmpty(){ for(int i=0;i<currentSize;i++){ array[currentSize]=null; } currentSize=0; } private static final int DEFAULT_CAPACITY=10; private int currentSize; private T[] array; private void percolateDown(int hole){ T tep=array[1]; for(int child=1;hole*2<currentSize;hole=child){ child=hole*2; if(array[child].compareTo(array[child+1])<0) child++; if(tep.compareTo(array[child])<0){ array[hole]=array[child]; }else{ break; } } array[hole]=tep; } private void buildHeap(){ for(int i=currentSize/2;i>0;i--){ percolateDown(i); } } private void enlargeArray(int newSize){ T[] oldArray=array; if(newSize<currentSize){ return; } array=(T[]) new Object[newSize]; for(int i=1;i<currentSize;i++){ array[i]=oldArray[i]; } } }

 

posted @ 2017-10-03 17:51  竹马今安在  阅读(543)  评论(0编辑  收藏  举报