Cod sursa(job #1385824)

Utilizator andru47Stefanescu Andru andru47 Data 12 martie 2015 14:04:08
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <cstdio>
#include <algorithm>
#define NMAX 500001
using namespace std;
int n,a[NMAX],i,nn;
void comb(int poz,int n)
{
    int x1,x2;
    if (2*poz<=n)
    {
        x1=a[2*poz];
        if (2*poz+1>n)x2=x1-1;
        else x2=a[2*poz+1];
        if (x1>=x2)
        {
            if (x1>a[poz])
            {
                swap(a[2*poz],a[poz]);
                comb(2*poz,n);
            }
        }
        else
        {
            if (x2>a[poz])
            {
                swap(a[2*poz+1],a[poz]);
                comb(2*poz+1,n);
            }
        }
    }
    return ;
}
int main()
{
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d\n",&n);
    for (i=1; i<=n; i++)
        scanf("%d ",&a[i]);
    for (i=n/2; i>=1; i--)
    {
        comb(i,n);
    }
    nn=n;
    while (nn>0)
    {
        swap(a[1],a[nn]);
        nn--;
        comb(1,nn);
    }
    for (i=1; i<=n; i++)
        printf("%d ",a[i]);
    return 0;
}