堆排(模板)
堆排序
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1005;
int n,a[MAXN],f[MAXN],t,siz;
inline void pus(int x){
f[++t]=x;
int now=t;
while(now>1){
if(f[now]>f[now/2]) break;
swap(f[now],f[now/2]);
now/=2;
}
}
inline void del(){
int now=1;
while(2*now<siz){
int tp=2*now;
if(f[tp]>f[tp+1] && tp+1<siz) tp++;
if(f[now]>f[tp]){
swap(f[now],f[tp]);
now=tp;
}
else break;
}
}
int main(){
scanf("%d",&n);
for(register int i=1;i<=n;i++){
scanf("%d",&a[i]);
pus(a[i]);
}
for(siz=n;siz>=2;siz--){
swap(f[1],f[siz]);
del();
}
for(register int i=1;i<=n;i++)
printf("%d ",f[i]);
return 0;
}