Pagini recente » Cod sursa (job #677006) | Cod sursa (job #2673864) | Cod sursa (job #943966) | Cod sursa (job #1850764) | Cod sursa (job #1574135)
#include <bits/stdc++.h>
#define N 500100
using namespace std;
int n;
int tab[N];
void siftdown(int *a, int start, int end);
void heapify(int *a, int count);
// HEAPSORT
int parent(int i)
{
return (i-1)/2;
}
int leftchild(int i)
{
return 2*i+1;
}
int rightchild(int i)
{
return 2*i+2;
}
void heapsort(int *a, int count)
{
heapify(a,count);
int end = count - 1;
while(end>0)
{
swap(a[end],a[0]);
end--;
siftdown(a,0,end);
}
}
void heapify(int *a, int count)
{
int start = parent(count-1);
while(start>=0)
{
siftdown(a,start,count-1);
start--;
}
}
void siftdown(int *a, int start, int end)
{
int root = start;
while(leftchild(root)<=end)
{
int child = leftchild(root);
int tmp = root;
if(a[child]>a[tmp])
tmp = child;
if(child+1<=end && a[child+1]>a[tmp])
tmp = child+1;
if(tmp == root)
return;
else
{
swap(a[tmp],a[root]);
root = tmp;
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
freopen("algsort.in","r",stdin);
freopen("algsort.out","w",stdout);
cin>>n;
for(int i=0;i<n;++i)
cin>>tab[i];
heapsort(tab,n);
for(int i=0;i<n;++i)
cout<<tab[i]<<" ";
return 0;
}