Cod sursa(job #2589797)

Utilizator segtreapMihnea Andreescu segtreap Data 26 martie 2020 21:36:36
Problema Sortare prin comparare Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <algorithm>
#include <cstdio>
#include <iostream>

using namespace std;

const int N = 500000 + 7;
int n;
int a[N];

int main() {
  freopen ("algsort.in", "r", stdin);
  freopen ("algsort.out", "w", stdout);

  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
  }
  int x = 1;
  while (x * 2 <= n) {
    x *= 2;
  }
  x = 1;
  while (x <= n) {
    for (int i = n - x + 1; i >= 1; i--) {
      if (a[i] > a[i + x - 1]) {
        swap(a[i], a[i + x - 1]);
      }
    }
    for (int i = 1; i <= n - x + 1; i++) {
      if (a[i] > a[i + x - 1]) {
        swap(a[i], a[i + x - 1]);
      }
    }
    x *= 2;
  }
  x = 1;
  while (x <= n) {
    for (int i = n - x + 1; i >= 1; i--) {
      if (a[i] > a[i + x - 1]) {
        swap(a[i], a[i + x - 1]);
      }
    }
    for (int i = 1; i <= n - x + 1; i++) {
      if (a[i] > a[i + x - 1]) {
        swap(a[i], a[i + x - 1]);
      }
    }
    x *= 2;
  }
  for (int i = 1; i <= n; i++) {
    printf("%d ", a[i]);
  }
  printf("\n");
}