Cod sursa(job #1815227)

Utilizator Vally77FMI Calinescu Valentin Gelu Vally77 Data 24 noiembrie 2016 22:40:39
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream ka("algsort.in");
ofstream ki("algsort.out");

const int N_MAX = 500000;

int n, heap_size;
int heap[N_MAX + 1];

void coborare(int t)
{
    if(2 * t <= heap_size)
    {
        if(heap[t] > heap[2 * t])
        {
            if(2 * t + 1 <= heap_size && heap[2 * t + 1] < heap[2 * t])
            {
                swap(heap[t], heap[2 * t + 1]);
                coborare(2 * t + 1);
            }
            else
            {
                swap(heap[t], heap[2 * t]);
                coborare(2 * t);
            }

        }
        else if(2 * t + 1 <= heap_size && heap[2 * t + 1] < heap[t])
        {
            swap(heap[t], heap[2 * t + 1]);
            coborare(2 * t + 1);
        }
    }

}

int main()
{
    ka >> n;
    for(int i = 1; i <= n; i++)
        ka >> heap[i];
    heap_size = n;
    for(int i = n / 2; i >= 1; i--)
        coborare(i);
    for(int i = 1; i <= n; i++)
    {
        ki << heap[1] << " ";
        swap(heap[1], heap[heap_size]);
        heap_size--;
        coborare(1);
    }
}