Cod sursa(job #1629091)

Utilizator experiment322Alexandru-Damian Manea experiment322 Data 4 martie 2016 12:44:11
Problema Sortare prin comparare Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.65 kb
#include <stdio.h>

enum {
	N = 500000
};

static int hsize, heap[N];

static int GetChild(int pos, int second)
{
	int child;
	child = 2 * pos;
	if (second) {
		child += 2;
	} else {
		child += 1;
	}
	if (child < hsize) {
		return child;
	} else {
		return -1;
	}
}

static int GetMinChild(int pos)
{
	int child1, child2;
	child1 = GetChild(pos, 0);
	child2 = GetChild(pos, 1);
	if (child1 == -1) {
    	return -1;
    } else if (child2 == -1) {
    	return child1;
    } else {
    	return heap[child1] < heap[child2] ? child1 : child2;
    }
}

static int GetParent(int pos)
{
	return (pos - 1) / 2;
}

static void Swap(int *a, int *b)
{
	int temp;
	temp = *a;
	*a = *b;
	*b = temp;
}

static int HeapPop(void)
{
    int element, i, c;
    element = heap[0];
    heap[0] = heap[--hsize];
    i = 0;
    c = GetMinChild(i);
    while (c != -1 && heap[i] > heap[c]) {
    	Swap(&heap[i], &heap[c]);
    	i = c;
		c = GetMinChild(i);
	}
    return element;
}

static void HeapPush(int elem)
{
    int i, p;
    heap[hsize] = elem;
    i = hsize++;
    p = GetParent(i);
    while (heap[i] < heap[p]) {
    	Swap(&heap[i], &heap[p]);
        i = p;
        p = GetParent(i);
    }
}

int main(void)
{
    int i, n, nr;
    FILE * ifile = fopen("algsort.in", "r");
    FILE * ofile = fopen("algsort.out", "w");
    fscanf(ifile, "%i", &n);
    for (i = 0; i < n; ++i) {
        fscanf(ifile, "%i", &nr);
        HeapPush(nr);
    }
    for (i = 0; i < n; ++i) {
        fprintf(ofile, "%i ", HeapPop());
    }
    fprintf(ofile, "\n");
    fclose(ifile);
    fclose(ofile);
    return 0;
}