Pagini recente » Cod sursa (job #2678908) | Cod sursa (job #689382) | Cod sursa (job #2031558) | Cod sursa (job #2982373) | Cod sursa (job #1195586)
#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;
}