Cod sursa(job #2484655)

Utilizator stormy_weatherelena cristina stormy_weather Data 31 octombrie 2019 12:41:55
Problema Sortare prin comparare Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;

int father(int i) {
  return i / 2;
}

int left_son(int i) {
  return 2 * i;
}

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

void percolate(vector<int> &heap, int pos) {
    int val = heap[pos];
    while (pos > 1 && heap[father(pos)] < val) {
      heap[pos] = heap[father(pos)];
      pos = father(pos);
    }
    heap[pos] = val;
    return;
}

void sift(vector<int> &heap, int pos, int n) {
  int son;
  do {
    son = -1;
    if (left_son(pos) <= n) {
      son = left_son(pos);
      if (right_son(pos) <= n && heap[right_son(pos)] < heap[left_son(pos)])
        son = right_son(pos);
      if (heap[pos] > heap[son]) {
        swap(heap[pos], heap[son]);
        pos = son;
      } else {
        son = -1;
      }
    }
  } while (son > 0);

  return;
}

void make_heap(vector<int> &heap, int n) {
  for (int i = n / 2; i >= 1; i--)
      sift(heap, i, n);

  return;
}

void sort_heap(vector<int> &heap, int n) {
  vector<int> sorted_heap(n + 1);
  int l = n;
  for (int i = 1; i <= l; i++) {
    sorted_heap[i] = heap[1];
    swap(heap[1], heap[n]);
    n--;
    sift(heap, 1, n);
  }
  heap = sorted_heap;
}

int main() {
  int n; cin >> n;

  vector<int> a(n + 1);
  for (int i = 1; i <= n; i++)
    cin >> a[i];

  vector<int> heap = a;

  //make the vector a heap
  make_heap(heap, n);

  // sort the vector
  sort_heap(heap, n);

  for (int i = 1; i <= n; i++)
    cout << heap[i] << " ";
  cout << "\n";

  return 0;
}