Pagini recente » Cod sursa (job #803243) | Cod sursa (job #815484) | Cod sursa (job #180046) | Cod sursa (job #588156) | Cod sursa (job #410408)
Cod sursa(job #410408)
#include <fstream.h>
int N,K;
unsigned int Heap[500001];
void Read();
void Up(int what);
void Down(int what);
void HeapSort();
int main()
{
int i;
Read();
for(i=N>>1;i>=1;--i) Down(i);
HeapSort();
ofstream out("algsort.out");
for(i=1;i<=N;++i) out<<Heap[i]<<' ';
out.close();
return 0;
}
void Read()
{
ifstream in("algsort.in");
in>>N; K=N;
for(int i=1;i<=N;++i) in>>Heap[i];
in.close();
}
void Up(int what)
{
int key=Heap[what],father=what>>1;
while(1<what && Heap[father]<key)
{
Heap[what]=Heap[father];
what=father; father=what>>1;
}
Heap[what]=key;
}
void Down(int what)
{
int key=Heap[what],son,left,right;
do
{
son=0; left=what<<1;
if(left<=K)
{
son=left; right=left+1;
if(right<=K && Heap[right]>Heap[left]) son=right;
if(Heap[son]<key) son=0;
}
if(son){ Heap[what]=Heap[son]; what=son; }
}while(son);
Heap[what]=key;
}
void HeapSort()
{
int swap;
while(K>1)
{
swap=Heap[1]; Heap[1]=Heap[K]; Heap[K]=swap;
--K; Down(1);
}
}