Cod sursa(job #1195586)

Utilizator stef93Stefan Gilca stef93 Data 7 iunie 2014 23:38:27
Problema Sortare prin comparare Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.33 kb
#include <stdio.h>
#include <stdlib.h>

int heap[5000002];
int n, heapSize;

void swap(int *x, int *y) {
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
}

void pushHeap(int x) {
	int tata, fiu;
	heap[++heapSize] = x;

	fiu = heapSize;
	tata = fiu / 2;

	while (tata != 0) {
		if (heap[fiu] < heap[tata]) {
			swap((heap + fiu), (heap + tata));
		} else {
			break;
		}
		fiu = tata;
		tata = fiu / 2;
	}
}

void downHeap() {
	int tata = 1, fiu = 2;
	int minumum;
	while (fiu <= heapSize) {
		if (fiu + 1 <= heapSize && heap[fiu + 1] < heap[fiu]) {
			minumum = fiu + 1;
		} else {
			minumum = fiu;
		}
		fiu = minumum;
		if (heap[tata] > heap[fiu]) {
			swap((heap + tata), (heap + fiu));
		} else {
			break;
		}
		tata = fiu;
		fiu = tata * 2;
	}
}

int popHeap() {
	swap((heap + 1), (heap + heapSize));
	heapSize--;
	downHeap();

	return heap[heapSize + 1];
}

int main() {
	FILE * in = fopen("algsort.in", "r");
	FILE *out = fopen("algsort.out", "w");
	int i, x, j;

	fscanf(in, "%d", &n);

	for (i = 0; i < n; i++) {
		fscanf(in, "%d", &x);
		pushHeap(x);
//		for (j = 1; j <= heapSize; j++) {
//			fprintf(out, "%d ", heap[j]);
//		}
//		fprintf(out, "\n");
	}

	for (i = 0; i < n; i++) {
		fprintf(out, "%d ", popHeap());
//		popHeap();
//		for (j = 1; j <= heapSize; j++) {
//			fprintf(out, "%d ", heap[j]);
//		}
//		fprintf(out, "\n");
	}
	return 0;
}