Cod sursa(job #936470)

Utilizator toranagahVlad Badelita toranagah Data 7 aprilie 2013 12:56:45
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

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

const int MAX_N = 500100;
int N;
int v[MAX_N];
int heap_size = 0;

void heap_sort();
void make_heap();
void sift(int node);

int main() {
  fin >> N;
  
  for (int i = 1; i <= N; ++i) {
    fin >> v[i];
  }

  heap_sort();

  for (int i = 1; i <= N; ++i) {
    fout << v[i] << ' ';
  }

  return 0;
}

void heap_sort() {
  make_heap();

  while (heap_size > 1) {
    swap(v[1], v[heap_size]);
    --heap_size;
    sift(1);
  }
}

void make_heap() {
  heap_size = N;
  for (int i = heap_size / 2; i > 0; --i) {
    sift(i);
  }
}

void sift(int node) {
  int l = node * 2;
  int r = l + 1;
  
  int son = node;
  if (l <= heap_size) son = l;
  if (r <= heap_size && v[r] > v[l] ) {
    son = r;
  }
  
  if (v[son] > v[node]) {
    swap(v[son], v[node]);
    sift(son);
  }
}