Pagini recente » Cod sursa (job #2746427) | Cod sursa (job #976076) | Cod sursa (job #345057) | Cod sursa (job #2813699) | Cod sursa (job #758006)
Cod sursa(job #758006)
#include <fstream>
using namespace std;
const int N = 500005;
int v[N], heap[N], n;
ifstream in("algsort.in");
ofstream out("algsort.out");
inline void sch(int& a, int& b)
{
int c = a;
a = b;
b = c;
}
void up(int x)
{
while (x > 1 && heap[x] > heap[x/2])
{
sch(heap[x], heap[x / 2]);
x /= 2;
}
}
void down(int x)
{
int best = x;
do
{
sch(heap[x], heap[best]);
x = best;
if (2 * x <= heap[0] && heap[best] < heap[2 * x])
best = 2 * x;
if (2 * x < heap[0] && heap[best] < heap[2 * x + 1])
best = 2 * x + 1;
} while (best != x);
}
void push(int x)
{
heap[++heap[0]] = x;
up(heap[0]);
}
void pop()
{
heap[1] = heap[heap[0]--];
down(1);
}
void heapsort()
{
for (int i = 1 ; i <= n ; i++)
push(v[i]);
for (int i = n ; i ; i--)
{
v[i] = heap[1];
pop();
}
}
int main()
{
in >> n;
for (int i = 1 ; i <= n ; i++)
in >> v[i];
heapsort();
for (int i = 1 ; i <= n ; i++)
out << v[i] << " ";
out << "\n";
return 0;
}