Pagini recente » Cod sursa (job #950191) | Cod sursa (job #2478058) | Cod sursa (job #1077444) | Cod sursa (job #1697950) | Cod sursa (job #1052348)
#include <fstream>
#include <iostream>
using namespace std;
int heap[500001],n;
void shiftRight(int *heap, int i, int n)
{
int root=i;
while((root*2)<=n)
{
int left=root*2;
int right=left + 1;
int swapId=root;
if(heap[swapId]<heap[left])
swapId=left;
if(right<=n && heap[swapId]<heap[right])
swapId=right;
if(swapId!=root)
{
swap(heap[root],heap[swapId]);
root=swapId;
}
else
break;
}
}
void heapify(int *heap, int i, int n)
{
int mid=(n-i)/2;
while(mid>0)
{
shiftRight(heap,mid,n);
mid--;
}
}
void heapsort(int *heap, int n)
{
heapify(heap,1,n);
int m=n;
while(m)
{
swap(heap[m],heap[1]);
m--;
shiftRight(heap,1,m);
}
}
int main()
{
ifstream f("algsort.in");
ofstream g("algsort.out");
f>>n;
int nHeap=0;
int x;
for(int i=1;i<=n;i++)
f>>heap[i];
heapsort(heap,n);
for(int j=1;j<=n;j++)
g<<heap[j]<<" ";
return 0;
}