Cod sursa(job #767240)

Utilizator igsifvevc avb igsi Data 13 iulie 2012 00:25:06
Problema Sortare prin comparare Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 0.86 kb
#include<stdio.h>

typedef unsigned int uint;

uint v[500001], N, heapSize;
FILE *in, *out;

void heapify(uint pos)
{
	uint next = pos, aux;
	for(;;)
	{
		if((pos << 1) <= heapSize && (v[next] < v[pos << 1]))
			next <<= 1;
		if((pos << 1) + 1 <= heapSize && (v[next] < v[(pos << 1) + 1]))
			next = (pos << 1) + 1;
		
		if(next != pos)
		{
			aux = v[pos]; v[pos] = v[next]; v[next] = aux;
			pos = next;
		}
		else break;
	}
}

int main()
{
	uint aux, i;
	
	in = fopen("algsort.in", "r");
	out = fopen("algsort.out", "w");
	
	fscanf(in, "%d", &N);
	for(i = 1; i <= N; ++i)
		fscanf(in, "%d", &v[i]);
	
	heapSize = N;
	for(i = N >> 1; i; --i)
		heapify(i);
	
	for(; heapSize;)
	{
		aux = v[1]; v[1] = v[heapSize]; v[heapSize] = aux;
		--heapSize;
		heapify(1);
	}
	
	for(i = 1; i <= N; ++i)
		fprintf(out, "%d ", v[i]);
	fprintf(out, "\n");
		
	fclose(in);
	fclose(out);
	return 0;
}