Cod sursa(job #1315944)

Utilizator priestnoobFMI - Dan Nema priestnoob Data 13 ianuarie 2015 12:58:37
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include<stdio.h>
#include<algorithm>

using namespace std;
#define nmax 500005

int n,h[nmax];

inline int father(int nod){
return nod/2;
}

inline int ls(int nod){
return nod*2;
}

inline int rs(int nod){
return nod*2+1;
}

void faheap (int k,int n)
{
    int little;
    if(ls(k)<=n && h[ls(k)] > h[k] )
        little=ls(k);
    else little=k;
    if(rs(k)<=n && h[rs(k)] > h[little] )
        little=rs(k);
    if(little!=k)
    {
        swap(h[k],h[little]);
        faheap(little, n);
    }
}

void buildheap()
{
    for(int i=n/2;i>0;--i)
        faheap  (i,n);
}

void heapsort()
{
    for(int i=n;i>0;--i)
    {
        swap(h[1],h[i]);
        faheap(1,i-1);
    }
}

int main()
{
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
        scanf("%d",&h[i]);
    buildheap();
    heapsort();
    for(int i=1;i<=n;++i)
        printf("%d ",h[i]);
}