Cod sursa(job #1756764)

Utilizator theodor.moroianuTheodor Moroianu theodor.moroianu Data 13 septembrie 2016 16:55:30
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
using namespace std;
 
const int NMAX = 500010;
int v[NMAX];
int a, b, x, y, i, j, n;
int vsort[NMAX];
int z;
void tamise(int x);
void swap(int x, int y) {
    a = v[x];
    v[x] = v[y];
    v[y] = a;
}
 
int main() {
    ifstream in("algsort.in");
    in >> n;
    z = n;
    for (int i = 1; i <= n; i++) {
        in >> v[i];
    }
    v[n + 1] = 0;
    for (i = n / 2 + 1; i >= 1; i--)
        tamise(i);
    for (int i = 1; i <= z; i++) {
        vsort[i] = v[1];
        v[1] = v[n];
        v[n] = 0;
        n--;
        tamise(1);
    }
    ofstream out("algsort.out");
    for (int i = z; i >= 1; i--) {
        out << vsort[i] << ' ';
    }
}
 
void tamise(int x) {
    if (x > n / 2 + 1)
        return;
    if (v[x] < v[2 * x] && (v[2 * x] > v[2 * x + 1] || 2 * x + 1 > z)) {
        swap(x, 2 * x);
        tamise(2 * x);
    }
    if (v[x] < v[2 * x + 1] && 2 * x + 1 <= z) {
        swap(x, 2 * x + 1);
        tamise(2 * x + 1);
    }
}