Pagini recente » Cod sursa (job #2423937) | Cod sursa (job #1186333) | Cod sursa (job #2895615) | Cod sursa (job #1448995) | Cod sursa (job #2075855)
#include <fstream>
#include <vector>
class Heap {
private:
std::vector<int> h; /// structura de heap in sine
int Parent(const int &index) const {
return (index - 1) / 2;
}
int LeftSon(const int &index) const {
return 2 * index + 1;
}
int RightSon(const int &index) const {
return 2 * index + 2;
}
bool HasLeftSon(const int &index) const {
return 2 * index + 1 < (int)h.size();
}
bool HasRightSon(const int &index) const {
return 2 * index + 2 < (int)h.size();
}
bool IsLeaf(const int &index) const {
return !HasLeftSon(index);
}
void SwapNodes(const int &index1, const int &index2) {
std::swap(h[index1], h[index2]);
}
void Sift(int index) {
while (index > 0 && h[index] < h[Parent(index)]) {
SwapNodes(index, Parent(index));
index = Parent(index);
}
}
void Percolate(int index) {
while (!IsLeaf(index)) {
int son_with_lowest_key = LeftSon(index);
int son_lowest_key = h[son_with_lowest_key];
if (HasRightSon(index)) {
int right_son_key = h[RightSon(index)];
if (right_son_key < son_lowest_key) {
son_with_lowest_key = RightSon(index);
son_lowest_key = right_son_key;
}
}
if (son_lowest_key < h[index]) {
SwapNodes(index, son_with_lowest_key);
index = son_with_lowest_key;
} else {
break;
}
}
}
public:
Heap() {}
void Push(int key) {
h.push_back(key);
Sift(h.size() - 1);
}
int Pop() {
int ret = h[0];
SwapNodes(0, h.size() - 1);
h.pop_back();
// Percolate down the node from the root
Percolate(0);
return ret;
}
};
int main()
{
std::ifstream cin("algsort.in");
std::ofstream cout("algsort.out");
Heap h;
int n;
cin >> n;
for (int x, i = 1; i <= n; ++ i) {
cin >> x;
h.Push(x);
}
for (int i = 1; i <= n; ++ i) {
cout << h.Pop() << (i == n ? '\n' : ' ');
}
return 0;
}