原创
堆排序C++实现
2010-1-24 10:09
2913
7
7
分类:
软件与OS
#include <iostream>
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<leng;i++)
{
cout<<data<<"\t";
}
cout<<endl;
}
void heap::heapsort()
{
built_heap();
for(int i="leng-1";i>0;i--)
{
exchange(data[0],data);
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)
{
largest=l;
}
else
{
largest=i;
}
if(r<=heapsize&&data[r]>data[largest])
{
largest=r;
}
if(largest!=i)
{
exchange(data,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<leng;i++)
{
cout<<"请输入第"<<i+1<<"个数:\n";
cin>>data;
}
}
int main()
{
heap test;
test.output();
cout<<"排序中......\n";
test.heapsort();
test.output();
return 0;
}
文章评论(0条评论)
登录后参与讨论