Cod sursa(job #1082220)

Utilizator dan.ghitaDan Ghita dan.ghita Data 14 ianuarie 2014 12:35:49
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int n=0, v[500005], m, p, x;
void push(int x)
{
    v[++n]=x;
    int p=n;
    while(v[p]<v[p/2]&&p>1)
        swap(v[p], v[p/2]), p/=2;
 
}
 
void pop()
{
    g<<v[1]<<' ';
    swap(v[1], v[n--]);
    p=1;
    int s;
    while(2*p<=n)
    {
        s=2*p;
        if(2*p+1>n)
        {
            if(v[p]>v[s]) swap(v[p], v[s]);
            break;
        }
        else
        {
            if(v[s]<=v[s+1]&&v[p]>v[s]) swap(v[p], v[s]);
            else if(v[p]>v[s+1]) swap(v[p], v[s+1]), s++;
        }
        p=s;
    }
}
int main()
{
    f>>m;
    for(int i=1; i<=m; ++i)
        f>>x, push(x);
    for(int i=1; i<=m; ++i)
        pop();
 
    return 0;
}