#include
using namespace std;
class heap
{
public:
heap();
~heap();
void heapsort();
void output();
private:
int *data;
int heapsize;
int leng;
int parent(int i);
int left(int i);
int right(int i);
void heapify(int i);
void built_heap();
void exchange(int &a,int &b);
};
void heap::output()
{
cout<<"现在数组中的数字分别为:\n";
for(int i="0";i {
cout< }
cout<}
void heap::heapsort()
{
built_heap();
for(int i="leng-1";i>0;i--)
{
exchange(data[0],data[i]);
heapsize--;
heapify(0);
}
}
void heap::built_heap()
{
heapsize=leng-1;
for(int i="parent"(leng);i>=0;i--)
{
heapify(i);
}
}
void heap::exchange(int &a,int &b)
{
int temp="a";
a=b;
b=temp;
}
void heap::heapify(int i)
{
int l,r,largest;
l=left(i);
r=right(i);
if(l<=heapsize&&data[l]>data[i])
{
largest=l;
}
else
{
largest=i;
}
if(r<=heapsize&&data[r]>data[largest])
{
largest=r;
}
if(largest!=i)
{
exchange(data[i],data[largest]);
heapify(largest);
}
}
int heap::parent(int i)
{
return (i-1)/2;
}
int heap::right(int i)
{
return (2*i+2);
}
int heap::left(int i)
{
return (2*i+1);
}
heap::~heap()
{
delete[] data;
}
heap::heap()
{
cout<<"请输入您需要排序的数字:\n";
cin>>leng;
data=new int[leng];
for(int i="0";i {
cout<<"请输入第"< cin>>data[i];
}
}
int main()
{
heap test;
test.output();
cout<<"排序中......\n";
test.heapsort();
test.output();
return 0;
}
阅读(743) | 评论(0) | 转发(0) |