Cod sursa(job #3211921)

Utilizator raizoSoare Antonio raizo Data 10 martie 2024 18:18:12
Problema Sortare prin comparare Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#include <vector>
using namespace std;
std::ifstream in("algsort.in");
std::ofstream out("algsort.out");


template <typename Type>
class Heap {
private:
    // this is a min heap
    std::vector<Type> heap;
public:
    Heap() : heap{ 0 } {}

    void swap(Type& x, Type& y) {
        Type z = x;
        x = y;
        y = z;
    }

    Type pop() {
        Type x = heap[1];
        int ind = 1;
        int son = 2;
        swap(heap[1], heap[heap.size() - 1]);
        heap.erase(heap.begin() + heap.size() - 1);
        if (son < heap.size()) {
            if (son + 1 < heap.size() && heap[son] > heap[son + 1]) {
                son++;
            }
            while (heap[son] < heap[ind]) {
                swap(heap[son], heap[ind]);
                ind = son;
                son = ind * 2;
                if (son >= heap.size()) { break; }
                if (son + 1 < heap.size() && heap[son] > heap[son + 1]) {
                    son++;
                }
            }
        }
        return x;
    }

    void add(Type x) {
        int ind = heap.size();
        heap.push_back(x);
        while (heap[ind] < heap[ind / 2] && ind > 1) {
            swap(heap[ind], heap[ind / 2]);
            ind /= 2;
        }
    }

};

template <typename Type>
void heapSort(std::vector<Type>& vec) {
    Heap<Type> heap;
    for (int i = 0; i < vec.size(); i++) {
        heap.add(vec[i]);
    }
    for (int i = 0; i < vec.size(); i++) {
        vec[i] = heap.pop();
    }
}




int main()
{
    std::vector<int> vec;
    int n;
    in >> n;
    for (int i = 0; i < n; i++) {
        in >> vec[i];
    }
    heapSort(vec);
    for (int i = 0; i < vec.size(); i++) {
        out << vec[i] << " ";
    }

}