Cod sursa(job #384429)

Utilizator hulparuadrianhulparu adrian hulparuadrian Data 20 ianuarie 2010 02:56:52
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.76 kb
#include<stdio.h>
#include<stdlib.h>
#define SIZE 500005
int n, x[SIZE];

void heap(int i, int h)
{
int left = 2*i;
int right = 2*i+1;
int max = i;
if (x[left]>x[max]&&left<=h) max=left;
if (x[right]>x[max]&&right<=h) max=right;
if (max!=i)
{
int temp = x[i];
x[i] = x[max];
x[max] = temp;
heap(max,h);
}
		  }
void constrheap()
{
for(int i=n/2;i>=1;i--) heap(i,n);
}

void sortare()
{
constrheap();
int h=n;
while(h>1)
{
int temp = x[1];
x[1] = x[h];
x[h] = temp;
h--;
heap(1,h);
}
}

int main()
{
	freopen("algsort.in","r",stdin);
	freopen("algsort.out","w",stdout);
	scanf("%d",&n);
	for(int i=1; i<=n; scanf("%d",&x[i++]));
	fclose(stdin);
	sortare();
	for(int j=1; j<=n; printf("%d ",x[j++]));
	fclose(stdout);
	return 0;
}