Cod sursa(job #1233075)

Utilizator andru47Stefanescu Andru andru47 Data 24 septembrie 2014 17:31:41
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <cstdio>
#include <algorithm>
using namespace std;
int n,a[1000],i,x,nn;
void heapup(int n)
{
    if (n<=1)  return ;
    if (a[n/2]<a[n])
    {
        swap(a[n/2],a[n]);
        heapup(n/2);
    }
}
void heapdown(int n,int r)
{
    if (n<=1)return ;
    if (a[2*r]>a[2*r+1]&&2*r<=n)
    {
        if (a[2*r]>a[r]){swap(a[2*r],a[r]);}
        else return ;
    }
    else if (a[2*r]==a[2*r+1]&&2*r+1<=n)
    {
        if (a[2*r+1]>a[r]){swap(a[2*r+1],a[r]);}
        else return ;
    }
    else if (a[2*r]<a[2*r+1]&&2*r+1<=n)
    {
        if (a[2*r+1]>a[r]){swap(a[2*r+1],a[r]);}
        else return ;
    }
    return ;
}
int main()
{
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d ",&n);
    for (i=1;i<=n;i++)
        {
           scanf("%d",&x);
           a[i]=x;
           heapup(i);
        }
        nn=n;
    while (n>1)
    {
        swap (a[1],a[n]);
        n--;

        heapdown(n,1);

    }
    for (i=1;i<=nn;i++)
        printf("%d ",a[i]);
    return 0;
}