Cod sursa(job #2291348)

Utilizator lflorin29Florin Laiu lflorin29 Data 27 noiembrie 2018 21:56:40
Problema Sortare prin comparare Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 1e6 + 2;

int n, H[N], nr;

void add(int x) {
  H[++nr] = x;
  int poz = nr;
  while(poz > 1) {
    if(H[poz] < H[poz / 2]) {
      swap(H[poz], H[poz / 2]);
      poz /= 2;
    } else break;
  }
}

int minim() {
  return H[1];
}

void repara() {
  int poz = 1;
  while(2 * poz <= nr) {
    int cine = 2 * poz;
    if(2 * poz + 1 <= nr && H[2 * poz + 1] < H[2 * poz])
      cine = 2 * poz + 1;
    if(cine != -1 && H[cine] < H[poz]) {
      swap(H[poz], H[cine]);
      poz = cine;
    } else break;
  }
}
void heapSort() {
  for(int i = 1; i <= n; ++i) {
    cout << minim() << ' ';
    swap(H[1], H[nr]);
    nr--;
    repara();
  }
}
int main() {
  ifstream cin("algsort.in");
  ofstream cout("algsort.out");
  cin >> n;
  for(int i = 1; i <= n; ++i) {
    int x;
    cin >> x;
    add(x);
  }

  heapSort();
}