Cod sursa(job #894822)

Utilizator paulbotabota paul paulbota Data 26 februarie 2013 23:53:21
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <cstdio>
#define MAXN 500010


int h[2*MAXN+100],k,n;

void swap(int x,int y)
{
    int aux=h[x];
    h[x]=h[y];
    h[y]=aux;
}

void upheap(int i)
{
    while(i>1 && h[i/2]>h[i])
    {
        swap(i/2,i);
        i=i/2;
    }
}

void downheap(int i)
{
    int stg,dr,max=i;
    stg=2*i;
    dr=2*i+1;
    if(stg<=k && h[stg]<h[i])
        max=stg;
    if(dr<=k && h[dr]<h[max])
        max=dr;
    if(max!=i)
    {
        swap(max,i);
        downheap(max);
    }
}

void insert_heap(int val)
{
    h[++k]=val;
    upheap(k);
}

int extract_min()
{
    int min=h[1];
    swap(1,k);
    k--;
    downheap(1);
    return min;
}

int main()
{
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d",&n);
    int j;
    for(j=1;j<=n;j++)
    {
        int i;
        scanf("%d ",&i);
       insert_heap(i);
    }
    while(k)
    {
        printf("%d ",extract_min());
    }
    printf("\n");
    return 0;
}