堆排序
2012-07-22 19:48
295 查看
//堆排序 #include<fstream> using namespace std; int N; int a[20]; int parent(int i)//返回父节点位置 { return i/2; } int left(int i)//返回左子节点位置 { return 2*i; } int right(int i)//返回右子节点位置 { return 2*i+1; } void maxheap(int i)//将第i个位置变为最大堆,默认它的子树都是最大堆了 { int l=left(i); int r=right(i); int max=i; if(l<=N && a[l]>a[i]) max=l; if(r<=N && a[r]>a[max]) max=r; if(max!=i) { int temp=a[i]; a[i]=a[max]; a[max]=temp; maxheap(max); } } void buildmaxheap()//建立最大堆,分析知a数组中在N/2+1之后的所有节点都是叶子节点,所以就从i/2到1节点执行maxheap函数,建立最大堆 { for(int i=N/2;i>=1;i--) { maxheap(i); } } void maxheapsort()//最大堆排序 { buildmaxheap();//先建立最大堆 for(int i=N;i>1;i--) { //现在a[1]肯定是最大的,把它与最有一个a 交换,然后在进行N-1次maxheap(1),找到剩余最大者 int temp=a[1]; a[1]=a ; a =temp; N--; maxheap(1); } } void main() { ifstream fin ("input.in"); ofstream fout ("output.out"); fin>>N; int j=N; for(int i=1;i<=N;i++) fin>>a[i]; maxheapsort(); for(i=1;i<=j-1;i++) fout<<a[i]<<" "; fout<<a[j]<<endl; }