Cod sursa(job #2487723)

Utilizator Horia14Horia Banciu Horia14 Data 5 noiembrie 2019 18:15:08
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include<fstream>
#include<iostream>
#define heapSIZE 500000
using namespace std;

class Heap {
private:
    int heapSize;
    int heap[heapSIZE];
public:
    void readArray(string name_fin) {
        int i;
        ifstream fin(name_fin);
        fin >> heapSize;
        for(i = 0; i < heapSize; i++)
            fin >> heap[i];
        fin.close();
    }
    void heapDown(int i, int hSize) {
        int l, r, p;
        l = 2 * i + 1;
        r = 2 * i + 2;
        if(l < hSize && heap[i] > heap[l])
            p = l;
        else p = i;
        if(r < hSize && heap[p] > heap[r])
            p = r;
        if(p != i) {
            swap(heap[i], heap[p]);
            heapDown(p, hSize);
        }
    }
    void buildHeap() {
        for(int i = heapSize / 2 - 1; i >= 0; i--)
            heapDown(i, heapSize);
    }
    void heapSort(string name_fout) {
        ofstream fout(name_fout);
        int val, i;
        buildHeap();
        for(i = heapSize - 1; i >= 0; i--) {
            val = heap[0];
            swap(heap[0], heap[i]);
            heapDown(0, i);
            fout << val << " ";
        }
        fout << "\n";
        fout.close();
    }
};

int main() {
    Heap h;
    h.readArray("algsort.in");
    h.buildHeap();
    h.heapSort("algsort.out");
    return 0;
}