二叉堆的类架构:
public class BinaryHeap<AnyType extends Comparable<? super AnyType>> {
public BinaryHeap(){ //构造函数1,声明默认大小。
this(DEFAULT_CAPACITY);
}
public BinaryHeap(int Capacity){ //构造函数2,用户自定义或者根据对象个数设置容量大小。
currentSize = 0;
array = (AnyType[]) new Comparable[Capacity + 1];
}
public BinaryHeap(AnyType[] items){ //构造函数3,传入具体对象数组。
currentSize = items.length;
array = (AnyType[]) new Comparable[(currentSize+2)*11/10]; //初始化数组。
int i = 1;
for(AnyType item:items) //第一步,将对象全部放入数组。
array[i++] = item;
buildHeap(); //针对放入数组的所有对象,建堆。
}
public void insert(AnyType x){ //插入对象。
if(currentSize == array.length - 1)
enlargeArray(array.length*2 + 1); //扩容。
//优先堆为完全树,放在最后一个元素
int hole = ++currentSize;
//从最后一个元素开始上溯,直到寻找到合适的位置,存在hole中
for(array[0] = x; x.compareTo(array[hole/2])<0; hole/=2)
array[hole] = array[hole/2];
array[hole] = x; //赋值
}
public AnyType findMin(){
if(isEmpty())
throw new UnderflowException();
return array[1]; //对于最小堆,返回数组下标为1的对象内容即为最小元素。//数组下标为0处,存放其他信息。
}
public AnyType deleteMin(){
if(isEmpty())
throw new UnderflowException();
AnyType minItem = findMin();
array[1] = array[currentSize--];
percolateDown(1); //下滤。
return minItem;
}
public boolean isEmpty(){
return 0 == currentSize;
}
public void makeEmpty(){
currentSize = 0;
}
//堆中的属性:
private static final int DEFAULT_CAPACITY = 10;
private int currentSize;
private AnyType[] array;
private void percolateDown(int hole){ //下滤。
int child;
AnyType tmp = array[hole];
for(;hole*2 <= currentSize; hole = child){
child = hole*2;
//和两个儿子中较小的一个比较
if(child != currentSize &&
array[child+1].compareTo(array[child])<0)
child++;
//如果比儿子小,则把hole放入儿子中,同时在儿子位置继续
if(array[child].compareTo(tmp)<0)
array[hole] = array[child];
else
break;
}
array[hole] = tmp;
}
private void buildHeap(){ //建堆。
for(int i = currentSize/2; i>0; i--)
//从最后一个儿子开始倒着往前下溯
percolateDown(i);
}
private void enlargeArray(int newSize){ //之前数组已满,扩大数组容量。
//System.out.println("Enlarge array size from "+array.length+" to "+newSize);
AnyType[] old = array;
array = (AnyType[]) new Comparable[newSize];
for (int i = 0; i < old.length; i++) {
array[i] = old[i];
}
}
public static void main(String[] args) {
int numItems = 10000;
BinaryHeap<Integer> h = new BinaryHeap<Integer>( );
int i = 1;
for( i = 10000; i > 0; i-- )
h.insert( i );
//ERROR CHECK
for( i = 1; i < numItems; i++ )
if( h.deleteMin( ) != i )
System.out.println( "测试--- " + i );
}
}