Cod sursa(job #852104)

Utilizator chimistuFMI Stirb Andrei chimistu Data 10 ianuarie 2013 21:06:23
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <cstdio>
#include <cstdlib>
#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)
        return;
     if (heap[x/2]>heap[x])
     {
             swap(heap[x/2],heap[x]);
             up_heap(x/2);
             }
}

long long minim(long long a,long long b)
{
     if (a<b)
        return a;
     return b;
}

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

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;
}