数据结构中的最小堆问题
#include<iostream>using namespace std;
const int Defaultsize=10;
template<class E>
class Minheap
{
public:
Minheap(int sz=Defaultsize);
Minheap(E arr[],int n);
~Minheap(){delete[]heap;}
bool Removemin(E &x);
void siftdown(int start,int m);
protected:
E *heap;
int currentsize;
int maxheapsize;
};
template<class E>
Minheap<E>::Minheap(int sz)
{
maxheapsize=(Defaultsize<sz)?sz:Defaultsize;
heap=new E[maxheapsize];
if(heap==NULL)
{cerr<<"堆存储分配失败!"<<endl;exit(1);}
currentsize=0;
}
template<class E>
Minheap<E>::Minheap(E arr[],int n)
{
maxheapsize=(Defaultsize<n)?n:Defaultsize;
heap=new E[maxheapsize];
if(heap==NULL)
{cerr<<"堆存储分配失败!"<<endl;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--;
}
//我想把最小堆输出来,这应怎样写,输出求解决?
}
template<class E>
void Minheap<E>::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;}
}
}
template<class E>
bool Minheap<E>::Removemin(E &x)
{
if(!currentsize)
{cout<<"Heap empty"<<endl;return false;}
x=heap[0];heap[0]=heap[currentsize-1];
currentsize--;
siftdown(0,currentsize-1);
cout<<"最小堆从小到大排列为:"<<x<<" "<<endl;
return true;
}
int main()
{
int arr[10];
//Minheap<int> s;
cout<<"请输入最小堆的节点数:"<<endl;
for(int i=0;i<10;i++)
cin>>arr[i];
cout<<"排序后的最小堆为:"<<endl;
Minheap<int>(arr,10);//输出最小堆
//s.Removemin();//输出最小堆从小到大排列,主函数怎样调用
system("pause");
return 0;
}
好无奈,求大神解救!