Pagini recente » Cod sursa (job #55331) | Cod sursa (job #633879) | Cod sursa (job #1586880) | Cod sursa (job #2378730) | Cod sursa (job #1536621)
#include <iostream>
#include <fstream>
using namespace std;
const int nmax = 500005;
int heap[nmax],len = 0,n;
void push(int val);
void pop();
int main(){
freopen("algsort.in", "r", stdin);
freopen("algsort.out", "w", stdout);
scanf("%d", &n);
int m = n,a;
for (; m--;){
scanf("%d", &a);
push(a);
}
for (int i = 1; i < n; i++) {
pop();
}
for (int i = 1; i <= n; i++)
printf("%d ", heap[i]);
fclose(stdin);
fclose(stdout);
return 0;
}
inline int f(int x) { return x >> 1; };
inline int l(int x) { return x << 1; };
inline int r(int x) { return (x << 1) + 1; };
void push(int val){
heap[++len] = val;
int a = len;
while (heap[a] > heap[f(a)] && a != 1 ) {
swap(heap[a], heap[f(a)]);
a = f(a);
}
}
void pop() {
swap(heap[1], heap[len--]);
bool q = true;
int a = 1;
while (q) {
q = false;
if ( l(a) < len ) {
if (heap[l(a)] < heap[r(a)] && heap[r(a)] > heap[a]) {
swap(heap[a], heap[r(a)]);
a = r(a);
q = true;
}
else if (heap[r(a)] < heap[l(a)] && heap[l(a)] > heap[a]) {
swap(heap[a], heap[l(a)]);
a = l(a);
q = true;
}
}
else if (l(a) == len && heap[l(a)] > heap[a]) {
swap(heap[a], heap[l(a)]);
}
}
}