Pagini recente » Cod sursa (job #2908834) | Cod sursa (job #577559) | Cod sursa (job #87373) | Cod sursa (job #3268997) | Cod sursa (job #2890886)
#include <fstream>
#define DIM 500001
using namespace std;
int heap[DIM];
int n = 0;
void buildHeap()
{
for (int i = 2; i <= n; i++)
{
int j = i;
while (j > 1 && heap[j] > heap[j / 2])
{
swap(heap[j], heap[j / 2]);
j /= 2;
}
}
}
void rebuildHeap(int index)
{
int parent = 1, child = 2;
while (child <= index)
{
if (child + 1 <= index && heap[child + 1] > heap[child])
child++;
if (heap[parent] < heap[child])
swap(heap[parent], heap[child]);
else
break;
parent = child;
child *= 2;
}
}
int main()
{
ifstream fin ("algsort.in");
ofstream fout("algsort.out");
fin >> n;
for (int i = 1; i <= n; i++)
fin >> heap[i];
buildHeap();
for (int i = n; i >= 2; i--)
{
swap(heap[1], heap[i]);
rebuildHeap(i - 1);
}
for (int i = 1; i <= n; i++)
fout << heap[i] << ' ';
return 0;
}