二叉堆的实现代码

Posted 竹马今安在

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉堆的实现代码相关的知识,希望对你有一定的参考价值。

因为二叉堆满足完全二叉树,一颗高为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]; } } }

 

以上是关于二叉堆的实现代码的主要内容,如果未能解决你的问题,请参考以下文章

二叉堆的实现

二叉堆的高效实现

二叉堆的所有用途

数据结构与算法 通俗易懂讲解 二叉堆实现

数据结构--左式堆的思想和代码

暖*墟 #二叉堆# 大根堆的常见操作