Pagini recente » Cod sursa (job #415995) | Cod sursa (job #407815) | Cod sursa (job #2164595) | Cod sursa (job #2848052) | Cod sursa (job #2911900)
#include <fstream>
#define DIM 1000001
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
int n;
int heap[DIM];
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 heapSort()
{
for (int i = n; i >= 2; i--) {
swap(heap[1], heap[i]);
int parent = 1, child = 2;
while (child <= i - 1) {
if (child + 1 <= i - 1 && heap[child] < heap[child + 1])
child++;
if (heap[child] > heap[parent])
swap(heap[child], heap[parent]);
else
break;
parent = child;
child = 2 * parent;
}
}
}
int main()
{
fin >> n;
for (int i = 1; i <= n; i++)
fin >> heap[i];
buildHeap();
heapSort();
for (int i = 1; i <= n; i++)
fout << heap[i] << ' ';
return 0;
}