Cod sursa(job #2162724)

Utilizator mrhammerCiocan Cosmin mrhammer Data 12 martie 2018 13:12:33
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
vector<int> vec;
int heap_size;
void heapify(int pos)
{
    int c1 = 2*pos+1;
    int c2 = 2*pos+2;
    int maxx = -1;
    int maxx_pos;
    if(c1 <= heap_size-1)
    {
        maxx = vec[c1];
        maxx_pos = c1;
    }
    if(c2 <= heap_size-1)
    {
        if(vec[c2] > maxx)
        {
            maxx = vec[c2];
            maxx_pos = c2;
        }
    }
    if(maxx > vec[pos])
    {
        swap(vec[pos],vec[maxx_pos]);
        if(maxx_pos <= heap_size/2-1) heapify(maxx_pos);
    }
}
void create_heap(int heap_size)
{
    for(int i=0;i<=heap_size/2-1;i++)
    {
        heapify(i);
    }
}
void print_vec()
{
    for(int i=0;i<vec.size();i++)
    {
        fout<<vec[i]<<" ";
    }
}
void heap_sort()
{
    while(heap_size > 0)
    {
        swap(vec[0],vec[heap_size-1]);
        heap_size--;
        create_heap(heap_size);
    }
}
int n;
int main()
{
    int k1;
    fin>>n;
    for(int i=0;i<n;i++)
    {
        fin>>k1;
        vec.push_back(k1);
    }
    heap_size = vec.size();
    create_heap(heap_size);
    heap_sort();
    print_vec();
}