Cod sursa(job #1567408)

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

using namespace std;

const int MAX_N = 5e5 + 10;

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 step = 1; 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";
}