Cod sursa(job #1987334)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 30 mai 2017 13:36:14
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>

using namespace std;

const int nMax = 500005;

int n;
int v[nMax];

void citire()
{
    ifstream in("algsort.in");
    in >> n;
    for(int i = 1; i <= n; ++i)
        in >> v[i];
    in.close();
}

void CombHeap(int ind, int Heap_Size)
{
    int st;
    int dr;
    int next;
    while(2 * ind <= Heap_Size)
    {
        st = 2 * ind;
        dr = st + 1;
        if(dr > Heap_Size || v[st] > v[dr])
            next = st;
        else
            next = dr;
        if(v[ind] < v[next])
            swap(v[ind], v[next]), swap(ind, next);
        else
            break;
    }
}

void Make_Heap()
{
    for(int i = n / 2; i >= 1; --i)
        CombHeap(i, n);
}

inline int GetMax()
{
    return v[1];
}

inline void DeleteMax(int Heap_Size)
{
    swap(v[1], v[Heap_Size]);
    CombHeap(1, Heap_Size - 1);
}

void heap_sort()
{
    Make_Heap();
    int mx;
    for(int i = n; i >= 1; --i)
    {
        mx = GetMax();
        DeleteMax(i);
        v[i] = mx;
    }
}


void afisare()
{
    ofstream out("algsort.out");
    for(int i = 1; i <= n; ++i)
        out << v[i] << " ";
    out.close();
}

int main()
{
    citire();
    heap_sort();
    afisare();
    return 0;
}