Cod sursa(job #349344)

Utilizator mihaionlyMihai Jiplea mihaionly Data 19 septembrie 2009 10:04:58
Problema Sortare prin comparare Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <stdio.h>
typedef long long big;
typedef unsigned uint;
#define nmax 500001
uint n;
big H[nmax];
void swap(big &x,big &y)
 {
 big ax=x;
 x=y;
 y=ax;
 }
inline uint lson(uint x)
 {
 return 2*x;
 }
inline uint rson(uint x)
 {
 return 2*x+1;
 }
inline uint father(uint x)
 {
 return x/2;
 }
void up_up(big H[],int k,uint n)
 {
 while(k>1&&H[father(k)]>H[k])
  {
  swap(H[father(k)],H[k]);
  k=father(k);
  }
 }
void down(big H[],int k,uint n)
 {
 uint son=1;
 while(lson(k)<=n)
  {
  son=lson(k);
  if(rson(k)<=n&&H[rson(k)]<H[lson(k)])
   son=rson(k);
  if(H[k]<=H[son])
   break;
  else
   {
   swap(H[k],H[son]);
   k=son;
   }
  }

 }
int main()
 {
 FILE *f=fopen("algsort.in","r");
 FILE *g=fopen("algsort.out","w");
 fscanf(f,"%ld",&n);
 for(int i=1;i<=n;i++)
  {
  fscanf(f,"%ld",&H[i]);
  up_up(H,i,n);
  }
 for(int i=n;i>=2;i--)
  {
  swap(H[1],H[i]);
  down(H,1,i-1);
  }
 for(int i=n;i>=1;i--)
  fprintf(g,"%ld ",H[i]);
 return 0;
 }