Pagini recente » Cod sursa (job #2846440) | Cod sursa (job #2525440) | Cod sursa (job #2846437) | Cod sursa (job #2777990) | Cod sursa (job #2892371)
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
vector<int> heap;
int left(int x) {
return x * 2;
}
int right(int x) {
return x * 2 + 1;
}
void down(int index) {
int son;
while (true) {
int l = left(index), r = right(index);
son = 0;
if (l < heap.size()) {
if (r < heap.size()) {
son = (heap[l] < heap[r]) ? l : r;
} else {
son = l;
}
}
if (son && heap[index] > heap[son]) {
swap(heap[index], heap[son]);
index = son;
} else {
break;
}
}
}
int pop() {
int last = heap[1];
swap(heap[1], heap.back());
heap.pop_back();
down(1);
return last;
}
int n;
void read() {
ifstream in("algsort.in");
in >> n;
heap.resize(n + 1);
for (int i = 1; i <= n; i++) {
in >> heap[i];
}
}
void solve() {
ofstream out("algsort.out");
for (int i = n / 2; i >= 1; i--) {
down(i);
}
while (n--) {
out << pop() << " ";
}
}
int main() {
read();
solve();
return 0;
}