Pagini recente » Cod sursa (job #2073404) | Cod sursa (job #2570544) | Cod sursa (job #1176951) | Cod sursa (job #1034558) | Cod sursa (job #2000935)
#include <cstdio>
#include <algorithm>
#define BUF_SIZE 1 << 17
#define MAXN 500000
int n, v[MAXN];
FILE *fin = fopen("algsort.in", "r"), *fout = fopen("algsort.out", "w");
int pos = BUF_SIZE, poz = 0;
char buf[BUF_SIZE], buf2[BUF_SIZE], s[10];
inline char nextch() {
if (pos == BUF_SIZE) fread(buf, 1, BUF_SIZE, fin), pos = 0;
return buf[pos++];
}
inline int read(int &x) {
x = 0;
char ch = nextch();
while (!isdigit(ch)) ch = nextch();
while (isdigit(ch)) {
x = 10 * x + ch - '0';
ch = nextch();
}
return x;
}
inline void putch(char ch) {
buf2[poz++] = ch;
if (poz == BUF_SIZE) fwrite(buf2, 1, BUF_SIZE, fout), poz = 0;
}
inline void baga(int x) {
int k = 0;
do {
s[++k] = x % 10;
x /= 10;
} while(x);
for (; k; k--)
putch(s[k] + '0');
}
inline int tata(int p) {
return (p - 1) / 2;
}
inline int fiust(int p) {
return 2 * p + 1;
}
inline int fiudr(int p) {
return 2 * p + 2;
}
inline void coborare(int p) {
int q;
bool f = 1;
while (f && (q = fiust(p)) < n) {
if (fiudr(p) < n && v[fiudr(p)] > v[q])
q = fiudr(p);
if (v[q] > v[p]) {
std::swap(v[p], v[q]);
p = q;
} else f = 0;
}
}
inline void heapify() {
for (int i = tata(n - 1); i >= 0; i--)
coborare(i);
}
inline void heapSort() {
int cn = n;
while(n > 1) {
n--;
std::swap(v[0], v[n]);
coborare(0);
}
n = cn;
}
int main() {
read(n);
for (int i = 0; i < n; i++)
read(v[i]);
heapify();
heapSort();
for (int i = 0; i < n; i++) {
baga(v[i]);
if (i < n - 1)
putch(' ');
}
putch('\n');
fwrite(buf2, 1, poz, fout);
fclose(fin);
fclose(fout);
return 0;
}