最小堆

来源:互联网 发布:南京聚铭网络怎么样 编辑:程序博客网 时间:2024/04/30 07:10
// Author ssk//Time 2012 12 30 22:46#include<iostream>#include<stdio.h>using namespace std;const int DefaultSize=100;template <typename T>class MinHeap{public:MinHeap(int sz);        //构造空堆MinHeap(T arr[],int n);      //用数组初始化堆~MinHeap() { delete []heap;}  //析构函数bool IsEmpty() const{ return currentSize==0?true:false; }bool IsFull() const{ return (currentSize==maxHeapSize)?true:false; }bool Insert(T m);bool Del(const T &del); //删除最小的元素void Print(int start=0,int n=0);private:T *heap;        //堆中用来存储的数组int currentSize;     //堆中当前元素个数int maxHeapSize;     //堆中可存储的最大元素个数void siftDown(int m,int n);       //自下而上的上滑调整void siftUp(int m,int n);        //自上向下的下滑调整 };template<typename T>MinHeap<T>::MinHeap(int sz)    //注意前面的也要加模版T {maxHeapSize=(DefaultSize<sz)?sz:DefaultSize;heap=new T[maxHeapSize];currentSize=0;}template<typename T>MinHeap<T>::MinHeap(T arr[],int n){maxHeapSize=(DefaultSize<n)?n:DefaultSize;heap=new T[maxHeapSize];for(int i=0;i<n;++i) heap[i]=arr[i];currentSize=n;int currentPos=(n-2)/2;while(currentPos>=0){siftDown(currentPos,n-1);currentPos--;} }template<typename T>void MinHeap<T>::siftDown(int start,int m){int i=start;int j=2*start+1;            //j为其左子女,下标为从0开始计数的T temp=heap[i];           while(j<=m)        //m为最大下标 { if(j<m&&heap[j]>heap[j+1]) j++;       //选择两者之间较小的  if(temp<=heap[j]) break;        //父小于子女,则不需要调整 else {   heap[i]=heap[j]; i=j;j=2*i+1; }}heap[i]=temp;}template<typename T>void MinHeap<T>::siftUp(int start,int m){int i=start;int j=(i-1)/2;  //j为其父结点T temp=heap[i];while(j>=m){if(temp>=heap[j]) break;else{ heap[i]=heap[j]; i=j; j=(i-1)/2;}}heap[i]=temp;}template<typename T>void MinHeap<T>::Print(int start,int n){if(start>=currentSize)return ;Print(start*2+2,n+1);for(int i=0;i<n;++i)cout<<"  ";cout<<heap[start]<<"-->"<<endl;Print(start*2+1,n+1);} template<typename T>bool MinHeap<T>::Insert(T m){if(IsFull()) return false;heap[currentSize]=m;siftUp(currentSize,0);currentSize++;return true;}template<typename T>bool MinHeap<T>::Del(const T & del){if(IsEmpty()) return false;heap[0]=heap[currentSize-1];currentSize--;siftDown(0,currentSize-1);return true;}int main(){int arr[5]={1,2,5,4,3};MinHeap <int> heap(arr,5);heap.Print();int x;heap.Del(x);heap.Print();//system("pause");return 0;}


 

原创粉丝点击