Cod sursa(job #3363676)

Utilizator EricDimiCismaru Eric-Dimitrie EricDimi Data 21 august 2026 10:14:32
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 kb
#include <fstream>

using namespace std;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

struct MaxHeap
{
    int* heap;
    int n;

    void Init(int n, int* arr)
    {
        this->n = n;
        this->heap = arr;
        BuildHeap();
    }

    inline int Father(int node) { return node >> 1; }
    inline int LeftSon(int node) { return node << 1; }
    inline int RightSon(int node) { return node << 1 | 1; }

    inline int Max() { return heap[1]; }

    void Sift(int node)
    {
        int son;
        while((son = LeftSon(node)) <= n)
        {
            son = LeftSon(node);
            if(RightSon(node) <= n && heap[RightSon(node)] > heap[LeftSon(node)])
                son = RightSon(node);
            if(heap[node] >= heap[son])
                break;
            swap(heap[node], heap[son]);
            node = son;
        }
    }

    void Percolate(int node)
    {
        while(node > 1 && heap[node] > heap[Father(node)])
        {
            swap(heap[node], heap[Father(node)]);
            node = Father(node);
        }
    }

    void BuildHeap()
    {
        for(int i = n >> 1; i > 0; i--)
            Sift(i);
    }

    void Erase(int pos)
    {
        heap[pos] = heap[n];
        n--;

        if(pos > 1 && heap[pos] > heap[Father(pos)])
            Percolate(pos);
        else
            Sift(pos);
    }

    void Insert(int val)
    {
        n++;
        heap[n] = val;
        Percolate(val);
    }

    void HeapSort()
    {
        int m = n;
        while(n > 1)
        {
            swap(heap[1], heap[n]);
            n--;
            Sift(1);
        }
        n = m;
    }

    friend ostream& operator<<(ostream& out, const MaxHeap& maxHeap)
    {
        for(int i = 1; i <= maxHeap.n; i++)
            out << maxHeap.heap[i] << ' ';
        out << '\n';
        return out;
    }
};
MaxHeap maxHeap;

int main()
{
    int n;
    fin >> n;
    int* arr = new int[n + 1];
    for(int i = 1; i <= n; i++)
        fin >> arr[i];

    maxHeap.Init(n, arr);
    maxHeap.HeapSort();
    fout << maxHeap;

    delete[] arr;

    fin.close();
    fout.close();

    return 0;
}