这是一个有关于最小堆的算法源码。
/*
*Heap.h
*/
#include<iostream>
using namespace std;
template<class T>
class Heap
{
private:
T * heap; //Point to the heap array
int size; //Maxsize of the Heap
int n; //Number of element in the heap
void siftdown(int ); //Put element in its correst place
public:
Heap(T * h,int num, int max){
heap=h;
n=num;
size=max;
buildHeap ();
}
~Heap(){}
int heapSize() const {
return size;
}
bool isLeaf(int pos) const {
return (pos >= n/2 )&&( pos < n );
}
int leftChild(int pos) const{
return pos*2+1;
}
int rightChild(int pos) const{
return pos*2+2;
}
int parent (int pos){
return pos/2;
}
bool insert(const T&);
bool removemin( ); //移除堆顶
bool remove(int ,T &); //移除指定位置的数据
void buildHeap(){
for(int i = n/2-1 ; i >= 0 ; i-- )
siftdown( i );
}
inline void swap(T A[], int i, int j) {
T temp = A[i];
A[i] = A[j];
A[j] = temp;
}
};
/*
*Heap.cpp
*/
#include"Heap.h"
template <class T>
void Heap<T>::siftdown(int pos){
while(!isLeaf(pos)){
int lc = leftChild(pos);
int rc = rightChild(pos);
if ((rc<n)&&(heap[lc]>heap[rc])) lc = rc;
if (heap[pos]>=heap[lc]) return;
swap(heap,pos ,lc);
pos=lc;
}
}
template<class T>
bool Heap<T> :: insert(const T & key){
if(n>=size) return false;
int curr = n++;
heap[curr] = key;
while ((curr != 0) &&( heap[curr]<=heap[parent(curr)])){
swap(heap,curr,parent(curr));
curr=parent(curr);
}
return true;
}
template <class T>
bool Heap<T>::removemin(){ //T & key
if(n==0) return false;
swap(heap,0,--n);
if(n != 0) siftdown(0);
//key =heap[n];
return true;
}
template <class T>
bool Heap<T>::remove(int pos , T & key){
if ( (pos<0)||(pos>=n) )return false;
swap(Heap,pos,--n);
while ((pos!=0)&&(heap[pos]<=heap[parent(pos)])){
swap(heap,pos,parent(pos));
}
siftdown(pos);
key = heap[n];
return true;
};