Cod sursa(job #1051675)

Utilizator sateanuAldea Andrei sateanu Data 10 decembrie 2013 13:29:14
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>
#include <iostream>
using namespace std;
int heap[500001],n,rez[500001];



void heapify(int *heap, int n, int i)
{
    if(i<=n)
    {
        if(heap[i]>heap[2*i]&&2*i<=n)
            swap(heap[i],heap[2*i]);
        if(heap[i]>heap[2*i+1]&&2*i + 1 <=n)
            swap(heap[i],heap[2*i+1]);

        heapify(heap,n,2*i);
        heapify(heap,n,2*i + 1);
    }
}

int decapit(int *heap, int &n)
{
    int minim=heap[1];
    swap(heap[1],heap[n]);
    n--;
    heapify(heap,n,1);
    return minim;
}

void ins(int *heap, int &n, int x)
{
    heap[++n]=x;
    heapify(heap,n,1);
}

int main()
{
    ifstream f("algsort.in");
    ofstream g("algsort.out");
    f>>n;
    int nHeap=0;
    int x;
    while(f>>x)
    {
        ins(heap,nHeap,x);
    }
    int i=0;
    while(nHeap>0)
    {
        rez[i++]=decapit(heap,nHeap);
    }
    for(int j=0;j<i;j++)
        g<<rez[j]<<" ";
    return 0;

}