#pragma once
#ifndef _MAXHEAP_H_
#define _MAXHEAP_H_
#define DefaultSize 10
template <class T>
class MaxHeap
{
public:
MaxHeap(int sz=DefaultSize)
{
maxHeapSize=(sz>DefaultSize) ? sz : DefaultSize;
heap=new T[maxHeapSize];
if(heap==NULL) exit(1);
currentSize=0;
}
MaxHeap(int arr[], int n)
{
maxHeapSize=(n>DefaultSize) ? n : DefaultSize;
heap=new T[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--;
}
}
~MaxHeap() {delete [] heap;}
bool Insert(const T& x)
{
if(currentSize=maxHeapSize) return false;
heap[currentSize]=x;
siftUp(currentSize);
currentSize++;
return true;
}
bool Remove(T& 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--)
{
T temp=heap[0]; heap[0]=heap[i]; heap[i]=temp;
siftDown(0, i-1);
}
}
private:
void siftDown(const int start, const int m)
{
int i=start; int j=2*i+1;
T 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;
T temp=heap[j];
while(j>0)
{
if(heap[i]<temp) {heap[j]=heap[i]; j=i; i=(j-1)/2;}
else break;
}
heap[j]=temp;
}
private:
T *heap;
int currentSize;
int maxHeapSize;
};
#endif
最大堆和堆排序
最新推荐文章于 2023-09-21 13:21:58 发布