Cod sursa(job #2911900)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 4 iulie 2022 14:18:11
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <fstream>
#define DIM 1000001

using namespace std;

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

int n;
int heap[DIM];

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 heapSort()
{
    for (int i = n; i >= 2; i--) {
        swap(heap[1], heap[i]);

        int parent = 1, child = 2;
        while (child <= i - 1) {
            if (child + 1 <= i - 1 && heap[child] < heap[child + 1])
                child++;
            if (heap[child] > heap[parent])
                swap(heap[child], heap[parent]);
            else
                break;

            parent = child;
            child = 2 * parent;
        }
    }
}

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

    buildHeap();
    heapSort();

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

    return 0;
}