Cod sursa(job #240074)

Utilizator toni2007Pripoae Teodor Anton toni2007 Data 6 ianuarie 2009 20:02:26
Problema Sortare prin comparare Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 0.79 kb
/*

Heap Sort

*/

#include <stdio.h>
#define  N 1000001
int h[N];
inline void swap(int a,int b){
     int aux;
     aux=h[a];
     h[a]=h[b];
     h[b]=aux;
}
inline void down_heap(int i,int n,int h[]){
     int max=i;
     if (2*i<=n && h[max]<h[2*i])
       max=2*i;
     if (2*i+1<=n && h[max]<h[2*i+1])
        max=2*i+1;
     if (i!=max){
        swap(i,max);
        down_heap(max,n,h);
     }
}
int main(){
    int i,n;
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d",&n);
    for (i=1;i<=n;++i)
       scanf("%d",&h[i]);
    for (i=n/2;i>=1;--i)
        down_heap(i,n,h);
    for (i=n;i>=1;--i){
        swap(1,i);
        down_heap(1,i-1,h);
    }
    for (i=1;i<=n;++i)
       printf("%d ",h[i]);
    return 0;
}