#include <stdio.h>
#include <stdlib.h>
#define NMAX 200000
int heap[NMAX] ;
void swap (int x, int y ) {
int aux ;
aux = heap[x] ;
heap[x] = heap[y] ;
heap[y] = aux ;
}
int father (int poz ) {
return poz / 2 ;
}
int right_son (int poz ) {
return poz * 2 + 1 ;
}
int left_son (int poz) {
return poz * 2 ;
}
int cautare_maxim () {
return heap[1] ;
}
void sift (int N, int k ) { /// Nodul de pe poz. k
int son ;
do {
son = 0 ;
if (left_son(k) <= N ) { /// Nu e frunza
son = left_son(k) ;
if (right_son(k) <= N && heap[right_son(k)] > heap[left_son(k)] )
son =right_son(k) ;
if ( heap[son] > heap[k] ) {
swap (k, son ) ;
k = son ;
}
else
son = 0 ;
}
}while (son != 0 ) ;
}
void precolate (int n, int k ) {
while (k > 1 && heap[father(k)] < heap[k] ){
printf ("%d", k ) ;
swap (k, father(k) ) ;
k = father(k) ;
}
}
void build_heap (int n ) {
int i ;
for (i = n / 2 ; i > 0 ; i-- ) {
sift(n, i) ;
}
}
void cut(int n, int k ) {
swap(k, n ) ; /// Il punem pe ultima pozitie
n--;
if (k > 1 && heap[k] > heap[father(k)] ) /// Daca e mai mare ca tatal sau il "promovam"
precolate(n, k) ;
else
sift(n, k ) ;
}
int insert (int n, int x ) {
heap[n+1] = x ;
n++;
precolate (n, n ) ;
return n ;
}
void heapsort (int n ) {
build_heap(n) ;
for (n = n ; n > 0 ; n-- ) {
swap (n, 1) ;
sift (n-1, 1 ) ;
}
}
int main()
{
/// Testez heapsort
int n, i, k ;
FILE *fin, *fout ;
fin = fopen ("algsort.in", "r" ) ;
fout = fopen ("algsort.out", "w" ) ;
fscanf (fin, "%d", &n ) ;
for (i = 1 ; i <= n ; i++ ) {
fscanf(fin, "%d", &heap[i] ) ;
}
heapsort (n) ;
for (i = 1 ; i <= n ; i++ ) {
fprintf (fout, "%d ", heap[i] ) ;
}
return 0;
}