HeapSort

来源:互联网 发布:森田玻尿酸乳液知乎 编辑:程序博客网 时间:2024/06/14 01:57
#include <iostream>using namespace std;//find the maxnmal numbera and put it to the place 0 void FindMaxInHeap(int a[],int size){for(int i = size -1;i > 0;i--){int parent = i / 2;int child = i;//if(i < size-1 && a[i] < a[i+1]){//cout<<"CHILD"<<child<<endl;//child++;//}if(a[child] > a[parent]){swap(a[child],a[parent]);}}}//for each root, find the max number...void HeapSort(int a[],int size){for(int i = size ;i > 0;i--){FindMaxInHeap(a,i);swap(a[0],a[i-1]);}}int main(){int n;while(cin>>n && n!=0){int a[1001];for(int i=0;i<n;i++){cin>>a[i];}HeapSort(a,n);for(int i=0;i<n-1;i++){cout<<a[i]<<' ';}cout<<a[n-1]<<endl;}} 

0 0
原创粉丝点击