Cod sursa(job #1052355)

Utilizator sateanuAldea Andrei sateanu Data 11 decembrie 2013 08:45:57
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 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)<=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+1)/2;
    while(mid>0)
    {
        shiftRight(heap,mid,n);
        mid--;
    }
}
void print(int *heap, int n)
{
    for(int i=1;i<=n;i++)
        cout<<heap[i]<<" ";
    cout<<endl;
}
void heapsort(int *heap, int n)
{
    heapify(heap,1,n);
    int m=n;
    //print(heap,n);
    while(m>1)
    {
        swap(heap[m],heap[1]);
        m--;
        shiftRight(heap,1,m);
        //print(heap,n);

    }
}
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;

}