Cod sursa(job #1567402)

Utilizator ericptsStavarache Petru Eric ericpts Data 13 ianuarie 2016 10:51:17
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <cstring>
#include <iostream>

using namespace std;

const int MAX_N = 5e5 + 10;
const int BASE = 4;

int v[MAX_N];
int aux[MAX_N];

int n;

void merge(int i, const int step) {
  const int fst = i;


  int j = i + step;
  const int ui = min(i + step - 1, n);
  const int uj = min(j + step - 1, n);
  int st = 0;


  while(i <= ui && j <= uj) {
    ++st;
    if(v[i] < v[j])
      aux[st] = v[i++];
    else 
      aux[st] = v[j++];
  }

  if(i <= ui) {
    while(i <= ui)
      aux[++st] = v[i++];
  } else {
    while(j <= uj)
      aux[++st] = v[j++];
  }

  memcpy(&v[fst], &aux[1], st * sizeof(int));
}

void debug() {
  for(int i = 1; i <= n; ++i)
    cerr << v[i] << " " ;
  cerr << "\n";
}

void msort() {

  for(int i = 1; i <= n; i += BASE) {
    const int j = min(i + BASE - 1, n);
    for(int k = i + 1; k <= j; ++k) {
      const int val = v[k];
      int place = k;
      while(val < v[place - 1] && place > i) {
        v[place] = v[place - 1];
        place--;
      }
      v[place] = val;
    }
  }

  for(int step = BASE; step < n; step *= 2) {
    for(int i = 1; i + step <= n; i += 2 * step) {
      merge(i, step);
    }
  }
}

int main() {
  ifstream in("algsort.in");
  in >> n;
  for(int i = 1; i <= n; ++i)
    in >> v[i];
  in.close();
  msort();

  ofstream out("algsort.out");
  for(int i = 1; i <= n; ++i)
    out << v[i] << " ";
  out << "\n";
}