Cod sursa(job #852727)

Utilizator chimistuFMI Stirb Andrei chimistu Data 11 ianuarie 2013 17:42:26
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <cstdlib>
#include <cstdio>
#define maxn 500001

FILE*f=fopen("algsort.in","r");
FILE*g=fopen("algsort.out","w");

long long A[maxn],heap[maxn];
int n,ind;

void swap(long long &a,long long &b)
{
     long long aux;
     aux=a;
     a=b;
     b=aux;
     }

void up_heap(int x)
{
     if (x>1)
        if (heap[x/2]>heap[x])
        {
            swap(heap[x/2],heap[x]);
            up_heap(x/2);
            }
}

void down_heap(int x)
{
     int m;
     if (2*x<=ind)
     {
           m=2*x;
           if (2*x+1<=ind && heap[2*x+1]<heap[2*x])
              m=2*x+1;
           if (heap[m]<heap[x])
           {
                swap(heap[m],heap[x]);
                down_heap(m);}
     }
}

int main()
{
    int i;
    fscanf(f,"%d",&n);
    ind=0;
    for (i=1;i<=n;i++)
    {
        fscanf(f,"%lld",&A[i]);
        ind++;
        heap[ind]=A[i];
        up_heap(ind);
        }
    for (i=1;i<=n;i++)
    {
        fprintf (g,"%lld ",heap[1]);
        swap(heap[1],heap[ind]);
        ind--;
        down_heap(1);
        }
    return 0;
}