堆排序
2019-03-11 本文已影响0人
凌霄文强
#include<iostream>
using namespace std;
int main(){
int a[]={6,3,4,1,7,2,9,55,77,11,88,5};
int length=sizeof(a)/sizeof(a[0])-1;
for(int i=(length-1)/2; i>=0; i--){
int j=i;
while(true){
if(j*2+1>length || (j*2+2>length && a[j]>=a[j*2+1]) || (j*2+2<=length && a[j]>=a[j*2+1] && a[j]>=a[j*2+2]))
break;
if(j*2+2>length || a[j*2+1]>a[j*2+2]){
swap(a[j],a[j*2+1]);
j=j*2+1;
}
else{
swap(a[j],a[j*2+2]);
j=j*2+2;
}
}
}
swap(a[0],a[length]);
for(int length=sizeof(a)/sizeof(a[0])-2; length>0; length--){
int j=0;
while(true){
if(j*2+1>length || (j*2+2>length && a[j]>=a[j*2+1]) || (j*2+2<=length && a[j]>=a[j*2+1] && a[j]>=a[j*2+2]))
break;
if(j*2+2>length || a[j*2+1]>a[j*2+2]){
swap(a[j],a[j*2+1]);
j=j*2+1;
}
else{
swap(a[j],a[j*2+2]);
j=j*2+2;
}
}
swap(a[0],a[length]);
for(int i=0; i<sizeof(a)/sizeof(a[0]); i++)
cout<<a[i]<<" ";
cout<<endl;
}
return 0;
}