Pagini recente » Cod sursa (job #2309799) | Cod sursa (job #475410) | Cod sursa (job #2739216) | Cod sursa (job #2726453) | Cod sursa (job #1211988)
#include <iostream>
#include <stdio.h>
using namespace std;
typedef long long ll;
ll n,a[500000 + 100];
void swap(ll i, ll j){
ll aux = a[i];
a[i] = a[j];
a[j] = aux;
}
ll partition(ll a[],ll l, ll r){
ll i, j, p, t;
p = a[r];
i = l;
for(j = l; j <= r-1; j++) {
if(a[j] <= p) {
swap(i,j);
i++;
}
}
swap(i,r);
return i;
}
void quick(ll a[],ll p, ll q){
if(p < q){
ll m = partition(a,p,q);
quick(a,p,m - 1);
quick(a,m + 1, q);
}
}
ll heapSize;
void max_heapify(ll a[],ll i)
{
ll l = (i << 1) + 1, r = (i << 1) + 2,max;
if(l < heapSize && a[i] < a[l])
max = l;
else
max = i;
if(r < heapSize && a[r] > a[max])
max = r;
if(max != i){
swap(i,max);
max_heapify(a,max);
}
}
void build_heap(){
heapSize = n;
for(ll i = ((n - 1) >> 1); i >= 0; i--)
max_heapify(a,i);
}
void heap_Sort(){
build_heap();
for(ll i = n - 1; i > 0; i--){
swap(0,i);
heapSize--;
max_heapify(a,0);
}
}
int main(){
freopen("algsort.in","r",stdin);
freopen("algsort.out","w",stdout);
scanf("%lld",&n);
for(unsigned int i = 0; i < n; i++)
scanf("%lld",&a[i]);
//quick(a,0,n - 1);
heap_Sort();
for(unsigned int i = 0; i < n; i++)
printf("%lld ",a[i]);
return 0;
}