#pragma once
#ifndef _MINHEAP_H_
#define _MINHEAP_H_
#define DefaultSize 10
template <class E>
class MinHeap
{
public:
MinHeap(int sz=DefaultSize) //构造函数,建立空堆;
{
maxHeapSize=(DefaultSize<sz) ? sz : DefaultSize;
heap=new E[maxHeapSize];
if(heap==NULL) exit(1);
currentSize=0;
}
MinHeap(E arr[], int n) //构造函数,通过数组建堆;
{
maxHeapSize=(DefaultSize<n) ? n : DefaultSize;
heap=new E[maxHeapSize];
if(heap==NULL) exit(1);
for(int i=0; i<n; i++) heap[i]=arr[i];
currentSize=n;
int currentPos=(currentSize-2)/2;
while(currentPos>=0)
{
siftDown(currentPos, currentSize-1);
currentPos--;
}
}
~MinHeap() {delete [] heap;}
bool Insert(const E& x) //最小堆的插入算法;
{
if(currentSize==maxHeapSize) return false;
heap[currentSize]=x;
siftUp(currentSize);
currentSize++;
return true;
}
bool RemoveMin(E & x) //删除堆顶上的最小元素;
{
if(!currentSize) return false;
x=heap[0];
heap[0]=heap[currentSize-1]; //最后元素填补到堆顶;
currentSize--;
siftDown(0, currentSize-1);
return true;
}
bool IsEmpty() const {return currentSize==0;}
bool IsFull() const {return currentSize=maxHeapSize;}
void MakeEmpty() {currentSize=0;}
void HeapSort() //最小堆排序,从大到小;
{
for(int i=currentSize-1; i>=0; i--)
{
E temp=heap[0]; heap[0]=heap[i]; heap[i]=temp;
siftDown(0, i-1);
}
}
private:
void siftDown(int start, int m) //最小堆的下滑调整算法;
{
int i=start, j=2*i+1;
E temp=heap[i];
while(j<=m)
{
if(j<m&&heap[j]>heap[j+1]) j++;
if(temp<=heap[j]) break;
else {heap[i]=heap[j]; i=j; j=2*j+1;}
}
heap[i]=temp;
}
void siftUp(int start) //最小堆的上滑调整算法;
{
int j=start, i=(j-1)/2;
E temp=heap[j];
while(j>0)
{
if(heap[i]<=temp) break;
else {heap[j]=heap[i]; j=i; i=(i-1)/2;}
}
heap[j]=temp;
}
private:
E *heap;
int currentSize;
int maxHeapSize;
};
#endif