Pagini recente » Cod sursa (job #743629) | Cod sursa (job #20530) | Cod sursa (job #2452802) | Cod sursa (job #2960293) | Cod sursa (job #1831251)
#include <fstream>
using namespace std;
void swap(int &a, int &b) {
int aux = a;
a = b;
b = aux;
}
void sift(int *heap, int n, int k) {
int son;
do {
son = 0;
if (2 * k <= n) {
son = 2 * k;
if (2 * k + 1 <= n && heap[2 * k] < heap[2 * k + 1]) {
son = 2 * k + 1;
}
if (heap[son] <= heap[k]) {
son = 0;
}
}
if (son) {
swap(heap[son], heap[k]);
k = son;
}
} while (son);
}
void build_heap(int *heap, int n) {
for (int i = n / 2; i > 0; --i) {
sift(heap, n, i);
}
}
void heap_sort(int *heap, int n) {
for (int i = n; i > 1; --i) {
swap(heap[i], heap[1]);
sift(heap, i - 1, 1);
}
}
int main() {
int n, heap[500001];
ifstream in("algsort.in");
in >> n;
for (int i = 1; i <= n; ++i) {
in >> heap[i];
}
in.close();
build_heap(heap, n);
heap_sort(heap, n);
ofstream out("algsort.out");
for (int i = 1; i <= n; ++i) {
out << heap[i] << ' ';
}
out << '\n';
out.close();
return 0;
}