Cod sursa(job #2547937)

Utilizator Horia14Horia Banciu Horia14 Data 15 februarie 2020 21:20:28
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include<fstream>
#define MAX_N 500000
using namespace std;

int h[MAX_N + 1], heapSize;

void readArray() {
    ifstream fin("algsort.in");
    fin >> heapSize;
    for(int i = 1; i <= heapSize; i++)
        fin >> h[i];
    fin.close();
}

void Swap(int i, int j) {
    int aux = h[i];
    h[i] = h[j];
    h[j] = aux;
}

void heapDown(int i) {
    int l, r, minim;
    l = 2 * i;
    r = 2 * i + 1;
    if(l <= heapSize && h[l] < h[i])
        minim = l;
    else minim = i;
    if(r <= heapSize && h[r] < h[minim])
        minim = r;
    if(minim != i) {
        Swap(i, minim);
        heapDown(minim);
    }
}

void buildHeap() {
    for(int i = heapSize / 2; i >= 1; i--)
        heapDown(i);
}

void heapSort() {
    ofstream fout("algsort.out");
    int i, minim, n;
    n = heapSize;
    for(i = 1; i <= n; i++) {
        minim = h[1];
        Swap(1, heapSize);
        heapSize--;
        heapDown(1);
        fout << minim << " ";
    }
    fout << "\n";
    fout.close();
}

int main() {
    readArray();
    buildHeap();
    heapSort();
    return 0;
}