最小堆--MinHeap

这是一个有关于最小堆的算法源码。

/*
*Heap.h
*/
#include
using namespace std;

template
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 
void Heap::siftdown(int pos){
	while(!isLeaf(pos)){
		int lc = leftChild(pos);
		int rc = rightChild(pos);
		if ((rcheap[rc]))  lc = rc;
		if (heap[pos]>=heap[lc]) return;
		swap(heap,pos ,lc);
		pos=lc;
	}
}
template
bool Heap :: 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 
bool Heap::removemin(){  //T & key
	if(n==0) return false;
	swap(heap,0,--n);
	if(n != 0) siftdown(0);
	//key =heap[n];
	return true;
}
template 
bool Heap::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;
};

你可能感兴趣的:(C++心得分享,数据结构)