Cod sursa(job #854748)

Utilizator blechereyalBlecher Eyal blechereyal Data 13 ianuarie 2013 22:45:25
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
using namespace std;
#include <fstream>
#include <vector>
#include<stdlib.h>
#define father(nod) (nod/2)
#define left_son(nod) (nod*2)
#define right_son(nod) (nod*2+1)

ifstream f("algsort.in");
ofstream g("algsort.out");




void swap(int H[],int a,int b)
{int aux;
aux=H[a];
H[a]=H[b];
H[b]=aux;
}

void sift(int H[],int N,int K)
{
int son;
do
  {
  son=0;

  if (left_son(K) <= N)
     {
     son=left_son(K);
     if (( right_son(K)<=N ) && (H[right_son(K)] < H[left_son(K)]))
      son=right_son(K);
     }

  if (H[son]>=H[K]) son=0;

  if (son)
     {
     swap(H,son,K);
     K=son;
     }
  } while (son);
}

void percolate(int H[],int N,int K)
{
while ( ( H[K]<H[father(K)] ) && (father(K)>=1) )
 {swap(H,K,father(K));
 K=father(K);
 }

}



void del(int H[],int &N,int K)
{int i=1;

H[i]=H[N];N--;
if ( (K>1) && (H[K]>H[father(K)]) )
     percolate(H,N,K);
else
     sift(H,N,K);
}

void add(int H[],int &N,int val)
{
N++;
H[N]=val;
percolate(H,N,N);


}


int main()
{int N=0,n,x;
int *heap;
f>>n;
heap=(int*)malloc(n*sizeof(int));
for (int i=1;i<=n;i++)
{
f>>x;
add(heap,N,x);
}
while (N)
{g<<heap[1]<<" ";
del(heap,N,1);}


return 0;
}