#include <iostream>
using namespace std;
class maxheap
{
private:
int * heaparray;
int cursize;
int maxsize;
public:
maxheap(int *arr,int num,int max)
{
heaparray=arr;
cursize=num;
maxsize=max;
}
void build()
{
for(int i=cursize;i<maxsize;i++) heaparray[i]=-1;
for(int i=cursize/2-1;i>=0;i--) shiftdown(i);
}
bool isleaf(int pos)
{
if(cursize/2<pos) return true;
else return false;
}
bool Remove(int pos)
{
int temp=heaparray[cursize-1];
//heaparray[cursize]=heaparray[pos];
heaparray[pos]=temp;
shiftdown(pos);
cursize--;
return true;
}
void shiftdown(int pos)
{
int i=pos,j=2*i+1;
int temp=heaparray[i];
while(j<cursize)
{
if((j<cursize-1)&&(heaparray[j]<heaparray[j+1]))
j++;
if(temp<heaparray[j])
{
heaparray[i]=heaparray[j];
i=j;
j=j*2+1;
}
else break;
}
heaparray[i]=temp;
}
void shiftup(int pos)
{
int i=pos,j=(i-1)/2;
int temp=heaparray[i];
while(j!=0||i!=0)
{
if(heaparray[j]>temp) break;
else if(heaparray[j]==temp)
{
cout<<"ÒÑ´æÔÚ"<<endl;
break;
}
else
{
heaparray[i]=heaparray[j];
i=j;
j=(i-1)/2;
}
}
heaparray[i]=temp;
}
maxheap Insert(maxheap m,const int node)
{
m.heaparray[m.cursize++]=node;
m.build();
return m;
}
bool Insert(const int node)
{
heaparray[cursize++]=node;
shiftup(cursize-1);
}
void Show()
{
for(int i=0;i<cursize;i++)
{
cout<<heaparray[i]<<" ";
}
cout<<endl;
}
};
int main()
{
int a[20]={20,12,35,15,10,80,30,17,2,1};
maxheap mh(a,10,20);
for(int i=0;i<10;i++) cout<<a[i]<<" ";
cout<<endl;
cout<<"build:"<<endl;
mh.build();
mh.Show();
cout<<"insert 666:"<<endl;
mh.Insert(666);
mh.Show();
cout<<"insert 36:"<<endl;
mh.Insert(36);
mh.Show();
cout<<"remove pos:3"<<endl;
mh.Remove(3);
mh.Show();
cout<<"remove pos:0"<<endl;
mh.Remove(0);
mh.Show();
cout << "Hello world!" << endl;
return 0;
}
最大堆的实现
最新推荐文章于 2023-04-05 21:23:41 发布