Pagini recente » Cod sursa (job #3262050) | Cod sursa (job #1795237) | Cod sursa (job #1015708) | Cod sursa (job #3181895) | Cod sursa (job #1041934)
#include <fstream>
#include <iostream>
#include <algorithm>
#include <climits>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
const int MAX_N = 500005;
int n, a[MAX_N], Heap[MAX_N];
void push (int val) {
Heap[++Heap[0]] = val;
int key = Heap[0];
while (Heap[key] < Heap[key / 2] && key / 2) {
swap (Heap[key], Heap[key / 2]);
key = key / 2;
}
}
int pop() {
int minim = Heap[1];
swap (Heap[1], Heap[Heap[0]]);
Heap[0]--;
int key = 1, poz;
do {
int left_son = 2 * key;
int right_son = 2 * key + 1;
poz = -1;
if (left_son <= Heap[0])
poz = left_son;
if (poz != -1 && right_son <= Heap[0] && Heap[right_son] < Heap[poz])
poz = right_son;
if (poz != -1)
if (Heap[key] > Heap[poz]) {
swap (Heap[key], Heap[poz]);
key = poz;
} else
poz = - 1;
} while (poz != -1);
return minim;
}
int main() {
f >> n;
for (int i = 1; i <= n; i++) {
f >> a[i];
push (a[i]);
}
for (int i = 1; i <= n; i++) {
a[i] = pop();
}
for (int i = 1; i <= n; i++)
g << a[i] << " ";
return 0;
}