Cod sursa(job #2416440)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 27 aprilie 2019 16:04:48
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 500005;

int v[MAXN];
vector<int> heap;

void heapsus(int p){
    if(p == 1)
        return;
    if(heap[p] < heap[p / 2]){
        swap(heap[p], heap[p / 2]);
        heapsus(p / 2);
    }
}

void heapjos(int p){
    int f1 = 2 * p, f2 = 2 * p + 1, np = p;
    if(f1 < heap.size() && heap[p] > heap[f1]) np = f1;
    if(f2 < heap.size() && heap[np] > heap[f2]) np = f2;
    if(np != p){
        swap(heap[p], heap[np]);
        heapjos(np);
    }
}

void sorting(){
    int pos = 0;
    while(!heap.empty()){
        v[++pos] = heap[1];
        swap(heap[1], heap[int(heap.size() - 1)]);
        heap.pop_back();
        heapjos(1);
    }
}

int main()
{
    ifstream fin("algsort.in");
    ofstream fout("algsort.out");
    int n;
    fin >> n;
    heap.push_back(0);
    for(int i = 1; i <= n; ++i){
        fin >> v[i];
        heap.push_back(v[i]);
        heapsus(i);
    }
    sorting();
    for(int i = 1; i <= n; ++i)
        fout << v[i] << " ";
    return 0;
}