Cod sursa(job #3291293)

Utilizator and_Turcu Andrei and_ Data 3 aprilie 2025 23:53:29
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include<bits/stdc++.h>


void max_heapify(int poz,std::vector<int> &v,int size)
{
    int l = poz*2+1, r= poz*2+2, best=poz;
 
    if( v[l]>v[best] and l<size )    
        best = l ;
    if( v[r]>v[best] and r<size )
        best = r;

    if( poz != best )
    {
        std::swap( v[poz],v[best] );
        max_heapify( best,v,size );
    }   

}

void max_heap(std::vector<int> &v)
{
    int size = v.size();

    for(int i= size/2-1 ;i>=0;i-- )
        max_heapify(i,v,size);

}

void heapsort(std::vector<int> &v)
{
    max_heap(v);

    for(int i=v.size();i>=2;i--)
    {
        std::swap( v[i-1],v[0] );
        max_heapify( 0,v,i-1 );
    }
}

int main()
{
    int n;
    std::vector<int> a;
   
    std::ifstream fin("algsort.in");
    std::ofstream fout("algsort.out");

    fin >> n;
    for(int i=1;i<=n;i++)
    {
        int x;
        fin >> x;
        a.push_back(x);
    }

    heapsort(a);

    for(auto x:a)
        fout << x << " ";

    return 0;
}