Cod sursa(job #2892371)

Utilizator ViAlexVisan Alexandru ViAlex Data 21 aprilie 2022 19:19:59
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include<iostream>
#include<fstream>
#include<vector>

using namespace std;


vector<int> heap;

int left(int x) {
    return x * 2;
}

int right(int x) {
    return x * 2 + 1;
}

void down(int index) {
    int son;
    while (true) {
        int l = left(index), r = right(index);
        son = 0;

        if (l < heap.size()) {
            if (r < heap.size()) {
                son = (heap[l] < heap[r]) ? l : r;
            } else {
                son = l;
            }
        }

        if (son && heap[index] > heap[son]) {
            swap(heap[index], heap[son]);
            index = son;
        } else {
            break;
        }

    }
}

int pop() {
    int last = heap[1];
    swap(heap[1], heap.back());
    heap.pop_back();
    down(1);
    return last;
}

int n;

void read() {
    ifstream in("algsort.in");
    in >> n;
    heap.resize(n + 1);

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

void solve() {
    ofstream out("algsort.out");
    for (int i = n / 2; i >= 1; i--) {
        down(i);
    }
    while (n--) {
        out << pop() << " ";
    }
}

int main() {
    read();
    solve();
    return 0;
}