Cod sursa(job #2296089)

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

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] , 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;
        // Alege un fiu mai mare ca tatal.
        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]);  // Functie STL ce interschimba H[K] cu H[son].
            K = son;
        }
    } while (son);
}

void build_heap(Heap H, int N) {
    for (int i = N / 2; i > 0; --i) {
        sift(H, N, i);
    }
}

void heapsort(Heap H, int N) {
    build_heap(H, N);

    // Sorteaza vectorul.
    for (int i = N; i >= 2; --i) {
        swap(H[1], H[i]);
        sift(H, i - 1, 1);
    }
}

int main()
{
    int n , 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] << " " ;

 }