您的位置:首页 > 其它

HeapSort

2014-11-14 00:14 239 查看
#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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: