Pagini recente » Cod sursa (job #1254874) | Cod sursa (job #1767412) | Cod sursa (job #749552) | Cod sursa (job #2134091) | Cod sursa (job #731883)
Cod sursa(job #731883)
#include <cstdio>
#include <fstream>
#define LE 1000005
#include <algorithm>
using namespace std;
int N,H[LE],i;
int right_son(int e) {
return 2*e+1;
}
int left_son(int e) {
return 2*e;
}
int father(int e) {
return e/2;
}
void jos(int nod ) {
int good,son;
do {
good=0,son=0;
if (left_son(nod)<=N)
son=left_son(nod);
if (right_son(nod)<=N&&H[right_son(nod)]>H[son])
son=right_son(nod);
if (H[nod]<H[son]&&son) {
swap(H[son],H[nod]);
nod=son;
good=1;
}
}
while (good);
}
void build_heap(int N) {
int t;
for(t=N/2; t>=1; t--)
jos(t);
}
void sus(int nod) {
while (H[father(nod)]<H[nod]) {
swap(H[father(nod)],H[nod]);
nod=father(nod);
}
}
void heapsort() {
do {
swap(H[1],H[N]);
N--;
jos(1);
}
while (N>1);
}
int main() {
freopen("algsort.in","r",stdin);
freopen("algsort.out","w",stdout);
scanf("%ld",&N);
for(i=1; i<=N; ++i) scanf("%ld",&H[i]);
int en=N;
build_heap(N);
heapsort();
for(i=1;i<=en;++i) printf("%ld ",H[i]);
return 0;
}