Pagini recente » Cod sursa (job #3362718) | Cod sursa (job #3363788) | Cod sursa (job #3364383) | Cod sursa (job #3364390) | Cod sursa (job #3363688)
#include <fstream>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
struct MaxHeap
{
int* heap;
int n;
void Init(int n, int* arr)
{
this->n = n;
this->heap = arr;
BuildHeap();
}
inline int Father(int node) { return node >> 1; }
inline int LeftSon(int node) { return node << 1; }
inline int RightSon(int node) { return node << 1 | 1; }
inline int Max() { return heap[1]; }
void Sift(int node)
{
int son;
while((son = LeftSon(node)) <= n)
{
son = LeftSon(node);
if(RightSon(node) <= n && heap[RightSon(node)] > heap[LeftSon(node)])
son = RightSon(node);
if(heap[node] >= heap[son])
break;
swap(heap[node], heap[son]);
node = son;
}
}
void Percolate(int node)
{
while(node > 1 && heap[node] > heap[Father(node)])
{
swap(heap[node], heap[Father(node)]);
node = Father(node);
}
}
void BuildHeap()
{
for(int i = n >> 1; i > 0; i--)
Sift(i);
}
void HeapSort()
{
int m = n;
while(n > 1)
{
swap(heap[1], heap[n]);
n--;
Sift(1);
}
n = m;
}
friend ostream& operator<<(ostream& out, const MaxHeap& maxHeap)
{
for(int i = 1; i <= maxHeap.n; i++)
out << maxHeap.heap[i] << ' ';
out << '\n';
return out;
}
};
MaxHeap maxHeap;
int main()
{
int n;
fin >> n;
int* arr = new int[n + 1];
for(int i = 1; i <= n; i++)
fin >> arr[i];
maxHeap.Init(n, arr);
maxHeap.HeapSort();
fout << maxHeap;
delete[] arr;
fin.close();
fout.close();
return 0;
}