Cod sursa(job #1841067)

Utilizator horatiucheval2Horatiu Andrei Cheval horatiucheval2 Data 5 ianuarie 2017 11:42:08
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
using namespace std;

const int MAX = 500001;
int v[MAX];

void makeMaxHeap(int vec[], int len){
    for(int i = 1; i <= len; i++){
        int pos = i;
        while(pos > 1 && vec[pos] > vec[pos / 2]){
            swap(vec[pos], vec[pos / 2]);
            pos /= 2;
        }
    }
}

void sift(int heap[], int node, int len){
    if(2 * node > len){
        return;
    } //frunza

    if(2 * node == len){ //doar un fiu
        if(heap[2 * node] > heap[node]){
            swap(heap[2 * node], heap[node]);
        }
        return;
    }

    if(2 * node < len){
        if(heap[2 * node] <= heap[node] && heap[2 * node + 1] <= heap[node])
            return;
        int ind;
        if(heap[2 * node] > heap[2 * node + 1])
            ind = 2 * node;
        else
            ind = 2 * node + 1;
        swap(heap[node], heap[ind]);
        sift(heap, ind, len);
    }
}

void heapsort(int vec[], int n){
    makeMaxHeap(vec, n);
    int len = n;
    while(len >= 1){
        swap(vec[1], vec[len]);
        len--;
        sift(vec, 1, len);
    }
}

int main(){
    ifstream fin("algsort.in");
    ofstream fout("algsort.out");

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

    heapsort(v, n);

    for(int i = 1; i <= n; i++){
        fout << v[i] << " ";
    }

    fin.close();
    fout.close();
    return 0;
}