Cod sursa(job #1052350)

Utilizator sateanuAldea Andrei sateanu Data 11 decembrie 2013 08:28:20
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <fstream>
#include <iostream>
using namespace std;
int heap[500005],n;

void shiftRight(int *heap, int i, int n)
{
    int root=i;
    while((root*2) + 1<=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;
    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;

}