Description
用函数实现堆排序,并输出每趟排序的结果
输入格式
第一行:键盘输入待排序关键的个数n
第二行:输入n个待排序关键字,用空格分隔数据
输出格式
第一行:初始建堆后的结果
其后各行输出交换堆顶元素并调整堆的结果,数据之间用一个空格分隔
输入样例
10
5 4 8 0 9 3 2 6 7 1
输出样例
9 7 8 6 4 3 2 5 0 1
8 7 3 6 4 1 2 5 0 9
7 6 3 5 4 1 2 0 8 9
6 5 3 0 4 1 2 7 8 9
5 4 3 0 2 1 6 7 8 9
4 2 3 0 1 5 6 7 8 9
3 2 1 0 4 5 6 7 8 9
2 0 1 3 4 5 6 7 8 9
1 0 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
#include#include using namespace std; void print_array(int a[],int n) { for(int i=0;i cout< int tmp; tmp=a; a=b; b=tmp; } //维护堆的性质 void heapify(int a[],int n,int i) { int largest=i; int ilchild=i*2+1; int irchild=i*2+2; if(ilchild a[largest]) largest=ilchild; if(irchild a[largest]) largest=irchild; if(largest!=i) //如果a[i]不是最大值 { swap(a[i],a[largest]); //才要和最小值进行交换 heapify(a,n,largest); //交换后要维护largest节点大顶堆的性质 } } //利用大顶堆进行排序 void heap_sort(int a[],int n) { int i; //建大顶堆 //要维护原始堆每一个父节点的性质,0也是父节点 for(i=n/2-1;i>=0;i--) { heapify(a,n,i); } print_array(a,n); //排序 //对后n-1个数进行排序,只需要排序n-1趟,即i>0 for(i=n-1;i>0;i--) { swap(a[i],a[0]); heapify(a,i,0); //维护前i个节点大顶堆的性质 print_array(a,n); } } int main() { int n; cin>>n; int *a=(int*)malloc(sizeof(int)*n); for(int i=0;i cin>>a[i]; } heap_sort(a,n); return 0; }



