Pagini recente » Cod sursa (job #1484210) | Cod sursa (job #104164) | Cod sursa (job #2466063) | Cod sursa (job #3273754) | Cod sursa (job #1703160)
#include <stdio.h>
#include <algorithm>
#include <math.h>
using namespace std;
int v[500005],n;
int father(int i){
return (i>>1);
}
int left(int i){
if((i<<1) <= n){
return (i<<1);
}
return 0;
}
int right(int i){
if((i<<1)+1 <= n){
return (i<<1)+1;
}
return 0;
}
void ascend(int poz){
while(poz > 1 && v[poz] > v[father(poz)]){
swap(v[poz], v[father(poz)]);
poz >>= 1;
}
}
void descend(int poz){
while(poz <= n && (v[poz] < v[left(poz)] || v[poz] < v[right(poz)])){
if(v[left(poz)] > v[right(poz)]){
swap(v[poz], v[left(poz)]);
poz = poz<<1;
}else{
swap(v[poz], v[right(poz)]);
poz = (poz<<1)+1;
}
}
}
int main()
{
freopen("algsort.in", "r", stdin);
freopen("algsort.out", "w", stdout);
int i;
scanf("%d",&n);
for(i = 1;i <= n;i++){
scanf("%d",&v[i]);
ascend(i);
}
int nn = n;
for(;n;){
int ax = v[1];
v[1] = v[n];
v[n] = ax;
n--;
descend(1);
}
for(i = 1;i <= nn;i++){
printf("%d ",v[i]);
}
return 0;
}