#include <iostream>
using namespace std;
template <class T>
class MaxHeap{
T* heap;
int curSize;
int maxSize;
public:
MaxHeap(int maxSize=10)
{
maxSize=maxSize;
curSize=0;
heap=new T[maxSize+1];
}
~MaxHeap(){
delete heap;
}
//get the curSize of this heap
int Get_Size() const
{
return curSize;
}
//get the max value,at the first position of the array
T Get_Max()
{
if (curSize==0)
{
return NULL;
}
else
{
return heap[1];
}
}
//insert a new element into the heap
void insert(const T& x)
{
if (curSize==maxSize)
{
cout<<"the heap is full"<<endl;
return;
}
int i=++curSize;
while (i>=1&&x>heap[i/2])
{
heap[i]=heap[i/2];
i/=2;
}
heap[i]=x;
cout<<"insert successfully: "<<x<<endl;
}
//delete the element with the max value,and save it into the parameter
void DeleteMax(T& x)
{
if (curSize==0)
{
cout<<"the heap is empty,can not delete"<<endl;
x=-9999;
return;
}
x=heap[1];
heap[0]=heap[curSize--];
int i=1;
int ci=2;
while (ci<=curSize)
{
//ci是较大的孩子的位置
if (heap[ci]<heap[ci+1]&&ci<=curSize)
{
ci++;
}
if (heap[0]>heap[ci])
{
break;
}
else
{
heap[i]=heap[ci];//move up the ci
i=ci;
ci*=2;
}
}
heap[i]=heap[0];
}
void Init_heap(T a[],int size,int maxsize)
{
delete[] heap;
heap=new T[maxsize+1];
this->curSize=size;
this->maxSize=maxsize;
for (int j=1;j<=size+1;j++)
{
heap[j]=a[j-1];
}
for (int i=size/2;i>=1;i--)
{
T y=heap[i];//the root element of the current subtree
int c=2*i;//begin to find the position to place y
while (c<=size)
{
if (c<curSize&&heap[c+1]>heap[c])
{
c++;
}
if (y>=heap[c])
{
break;
}
heap[c/2]=heap[c];
c*=2;
}
heap[c/2]=y;
}
}
};
int main()
{
MaxHeap<int> hp;
int a[11]={-111,5,2,12,3,55,21,7,9,11,9};
cout<<"用数组a来初始化堆:"<<endl;
for(int i=1;i<11;i++)
cout<<a[i]<<" ";
cout<<endl;
hp.Init_heap(a,10,15);
int max;
cout<<"目前堆中最大值为:"<<hp.Get_Max()<<endl;
hp.DeleteMax(max);
cout<<"删除的堆中最大的元素为:"<<max<<endl;
cout<<"删除后,现在堆中最大的元素为:"<<hp.Get_Max()<<endl;
cout<<"现在堆的大小为:"<<hp.Get_Size()<<endl;
cout<<"向堆中插入新元素"<<endl;
hp.insert(22);
hp.insert(45);
hp.insert(214);
hp.insert(16);
hp.insert(21);
hp.insert(121);
hp.insert(111);
cout<<"插入后现在堆的大小为:"<<hp.Get_Size()<<endl;
cout<<"现在由大到小输出堆中元素"<<endl;
do
{
hp.DeleteMax(max);
if(max== -9999)
break;
cout<<max<<" ";
}while(1);
cout<<endl;
return 0;
}
C++最大Heap
最新推荐文章于 2024-08-10 16:41:29 发布