Cod sursa(job #2296546)

Utilizator Dragomiralexandru621@yahoo.comDragomir ionut alexandru [email protected] Data 4 decembrie 2018 19:36:44
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
const int MAX_HEAP = 16384;
typedef int Heap[MAX_HEAP];

inline int father( int nod ) {
    return nod / 2;
}

inline int left_son( int nod ) {
    return nod * 2 ;
}

inline int right_son( int nod ) {
    return nod * 2 + 1 ;
}

int nod , v[200005] , heap[3000000] , n , vp[200005] , l , k ;

void percolate( Heap H , int N , int K ) {
    int key = H[K];

    while ( ( K > 1 ) && ( key > H[father( K )] ) ) {
        H[K] = H[father(K)] ;
        K = father(K) ;
    }

    H[K] = key ;
}


void insert( Heap H, int& N, int key ) {
    H[++ N] = key ;
    percolate( H , N , N );
}

void sift( Heap H, int N, int K ) {
    int son ;
    do {
        son = 0;
        if (left_son( K ) <= N) {
            son = left_son(K);
            if ( right_son( K ) <= N && H[right_son( K )] > H[left_son( K )] ) {
                son = right_son( K );
            }
            if (H[son] <= H[K]) {
                son = 0;
            }
        }

        if (son) {
            swap( H[K] , H[son] );
            K = son;
        }
    } while ( son );
}

void heapsort(Heap H, int N) {

    for (int i = N; i >= 1; --i) {
        swap(H[1], H[i]);
        sift(H, i - 1, 1);
    }
}

int main()
{
    int  i , u ;

    f >> n ;
    for( i = 1; i <= n; i ++ )
    {
            f >> u ;
      int k = i ;
  insert( heap , k , u ) ;

    }
    heapsort( heap , n + 1) ;

     for( int j = 2 ; j <= n + 1 ; j ++ )
         g << heap[j] << " " ;

 }