Cod sursa(job #2053447)

Utilizator CriogeniXBociat Daniel Tiberiu CriogeniX Data 31 octombrie 2017 19:13:26
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
using namespace std;

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

const int NMax = 500000;
int X[NMax + 5],Heap[NMax + 5];
int N,NHeap;

void Read()
{
  fin >> N;
  for(int i = 1; i <= N; ++i)
    fin >> X[i];
}

void UpHeap(int X)
{
  int Father = X / 2;
  if(Father && Heap[Father] > Heap[X])
  {
    swap(Heap[Father],Heap[X]);
    UpHeap(Father);
  }
}

void DownHeap(int X)
{
  int Son1 = 2*X ,Son2 = 2*X+1,Son;
  if(Son1 > NHeap)
    return;
  if(Son1 == NHeap)
  {
    if(Heap[Son1] < Heap[X])
    {
      swap(Heap[Son1],Heap[X]);
      return;
    }
  }
  if(Heap[Son1] < Heap[Son2])
    Son = Son1;
  else
    Son = Son2;
  if(Heap[Son] < Heap[X])
    {
      swap(Heap[Son],Heap[X]);
      DownHeap(Son);
    }
}

void BuildHeap()
{
  for(int i = 1; i <= N; ++i)
  {
    Heap[++NHeap] = X[i];
    UpHeap(NHeap);
  }
}

void HeapSort()
{
  for(int i = 1; i <= N; ++i)
  {
    X[i] = Heap[1];
    Heap[1] = Heap[NHeap--];
    DownHeap(1);
  }
}

void Print()
{
  for(int i = 1; i <= N; ++i)
    fout << X[i] << " ";
}

int main()
{
    Read();
    BuildHeap();
    HeapSort();
    Print();
    return 0;
}