小根堆的实现
#include<iostream>
using namespace std;
#define DefaultSize 50
template<typename T>
class MinHeap
{
public:
MinHeap(int sz=DefaultSize)
{
maxHeapSize=(DefaultSize<sz)?sz:DefaultSize;
heap=new T[maxHeapSize];
currentSize=0;
}
MinHeap(T arr[],int n)
{
maxHeapSize=(Default<n)?n:DefaultSize;
heap=new T[maxHeapSize];
for(int i=0;i<n;i++){
heap[i]=arr[i];
}
currentSize=n;
int currentpos=(currentSize-2)/2;//从最后一层开始向下调整,直到第一行
while(currentpos>=0){
shiftDown(currentpos,currentSize-1);
currentpos--;
}
}
bool insert(const T& x)
{
if(currentSize==maxHeapSize)
{
cout<<"Heap Full"<<endl;
return false;
}
heap[currentSize]=x;
shiftup(currentSize);
currentSize++;
return true;
}
bool removemin(T& x){
if(!currentSize)
{
cout<<"Heap Empty!"<<endl;
return false;
}
x=heap[0];
heap[0]=heap[currentSize-1];
currentSize--;
shiftdown(0,currentSize-1);
return true;
}
void output(){
for(int i=0;i<currentSize;i++)
{
cout<<heap[i]<<" ";
}
cout<<endl;
}
protected:
void shiftdown(int start,int end)
{
int cur=start;
int min_child=2*child+1;
T temp=heap[cur];
while(cur<=end){
if(min_child<end&&heap[min_child]>heap[min_child++1])
min_child++;
if(temp<=heap[min_child])
break;
else
{
heap[cur]=heap[min_child];
cur=min_child;
min_child=2*min_child+1;
}
}
heap[cur]=temp;
}
void shiftup(int start){
int cur=start;
int parent=(cur-1)/2;
T temp=heap[cur];
while(cur>0){
if(heap[parent]<=temp)
break;
else{
heap[cur]=heap[parent];
cur=parent;
parent=(parent-1)/2;
}
}
heap[cur]=temp;
}
private:
T* heap;
int currentSize;
int maxHeapSize;
};
int main(int argc, char* argv[])
{
MinHeap<int> h;
h.Insert(8);
h.Insert(5);
h.Insert(7);
h.Insert(9);
h.Insert(6);
h.Insert(12);
h.Insert(15);
h.output();
int out;
cout << static_cast<int> (h.RemoveMin(out)) << endl;
h.output();
int arr[10] = { 15,19,13,12,18,14,10,17,20,11 };
MinHeap<int> h1(arr,10);
h1.output();
}