Cod sursa(job #2913583)

Utilizator Linca_AmaliaLinca Mihaela Amalia Linca_Amalia Data 15 iulie 2022 11:56:40
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
using namespace std;

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

int n, p, c, v[500005];
int main(){

    fin >> n;

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

    ///MaxHeap
    for ( int i = 2; i <= n; i++ ){
        int j = i;
        while ( j > 1 && v[j] > v[j/2] ){
            swap( v[j], v[j/2] );
            j /= 2;
        }
    }

    for ( int i = n; i >= 2; i-- ){
        swap( v[1], v[i] );
        p = 1;
        c = 2;
        while ( c <= i - 1 ){
            if ( c + 1 <= i - 1 && v[c] < v[c+1] )
                c++;
            if ( v[p] < v[c] )
                swap( v[p], v[c] );
            else
                break;
            p = c;
            c *= 2;

        }
    }

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

    return 0;
}