Cod sursa(job #712282)

Utilizator tudgal1001Profir Tudor tudgal1001 Data 13 martie 2012 11:37:58
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include<cstdio>
using namespace std;

int a[500005],n,dim_heap;

void interschimb (int x,int y)
{
    int aux;
    aux=a[x];
    a[x]=a[y];
    a[y]=aux;
}

void reconst_heap (int x)
{
    int max;
    if (2*x<=dim_heap && a[2*x]>a[x])
        max=2*x;
    else max=x;
    if (2*x+1<=dim_heap && a[2*x+1]>a[max])
        max=2*x+1;
    if (max!=x)
    {
        interschimb(x,max);
        reconst_heap(max);
    }
}

void build_heap ()
{
    dim_heap=n;
    for (int i=n/2; i>=1; i--)
        reconst_heap(i);
}

void heapsort()
{
    build_heap();
    for (int i=n; i>=2; i--)
    {
        interschimb(1,i);
        dim_heap--;
        reconst_heap(1);
    }
}

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