Cod sursa(job #2890886)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 16 aprilie 2022 21:37:10
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#define DIM 500001

using namespace std;

int heap[DIM];
int n = 0;

void buildHeap()
{
    for (int i = 2; i <= n; i++)
    {
        int j = i;
        while (j > 1 && heap[j] > heap[j / 2])
        {
            swap(heap[j], heap[j / 2]);
            j /= 2;
        }
    }
}

void rebuildHeap(int index)
{
    int parent = 1, child = 2;
    while (child <= index)
    {
        if (child + 1 <= index && heap[child + 1] > heap[child])
            child++;

        if (heap[parent] < heap[child])
            swap(heap[parent], heap[child]);
        else
            break;

        parent = child;
        child *= 2;
    }
}

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

    fin >> n;
    for (int i = 1; i <= n; i++)
        fin >> heap[i];

    buildHeap();
    for (int i = n; i >= 2; i--)
    {
        swap(heap[1], heap[i]);
        rebuildHeap(i - 1);
    }

    for (int i = 1; i <= n; i++)
        fout << heap[i] << ' ';

    return 0;
}