Pagini recente » Cod sursa (job #195302) | Cod sursa (job #2418942) | Cod sursa (job #349944) | Cod sursa (job #1733838) | Cod sursa (job #2484656)
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int father(int i) {
return i / 2;
}
int left_son(int i) {
return 2 * i;
}
int right_son(int i) {
return 2 * i + 1;
}
void percolate(vector<int> &heap, int pos) {
int val = heap[pos];
while (pos > 1 && heap[father(pos)] < val) {
heap[pos] = heap[father(pos)];
pos = father(pos);
}
heap[pos] = val;
return;
}
void sift(vector<int> &heap, int pos, int n) {
int son;
do {
son = -1;
if (left_son(pos) <= n) {
son = left_son(pos);
if (right_son(pos) <= n && heap[right_son(pos)] < heap[left_son(pos)])
son = right_son(pos);
if (heap[pos] > heap[son]) {
swap(heap[pos], heap[son]);
pos = son;
} else {
son = -1;
}
}
} while (son > 0);
return;
}
void make_heap(vector<int> &heap, int n) {
for (int i = n / 2; i >= 1; i--)
sift(heap, i, n);
return;
}
void sort_heap(vector<int> &heap, int n) {
vector<int> sorted_heap(n + 1);
int l = n;
for (int i = 1; i <= l; i++) {
sorted_heap[i] = heap[1];
swap(heap[1], heap[n]);
n--;
sift(heap, 1, n);
}
heap = sorted_heap;
}
int main() {
#ifdef INFOARENA
ifstream cin("algsort.in");
ofstream cout("algsort.out");
#endif
int n; cin >> n;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++)
cin >> a[i];
vector<int> heap = a;
//make the vector a heap
make_heap(heap, n);
// sort the vector
sort_heap(heap, n);
for (int i = 1; i <= n; i++)
cout << heap[i] << " ";
cout << "\n";
return 0;
}