Cod sursa(job #1757787)

Utilizator catalincraciunCraciun Catalin catalincraciun Data 15 septembrie 2016 20:46:03
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <iostream>
#include <fstream>
#include <vector>
#define NMax 500001

using namespace std;

ifstream f("algsort.in");
ofstream g("algsort.out");

int n;
int A[NMax];
vector<int> B;

void read() {
	f>>n;
	for (int i=1;i<=n;i++)
		f>>A[i];
	f.close();
}

void sort(int left, int right) {
	if (left < right) {
		int mij = (left+right)/2;
		sort(left, mij);
		sort(mij+1, right);

		// Merging the two sides
		int x = left;
		int y = mij+1;
		int p = left-1;

		B.resize(1);
		for (int i=left;i<=right;i++) {
			B.push_back(A[i]);
		}
		
		int i;
		for (i=left;x <= mij && y <= right;i++) {
			if (B[x-p] < B[y-p]) {
				A[i] = B[x-p];
				x++; 	
			} else {
				A[i] = B[y-p];
				y++;
			}
		}

		while (x <= mij) {
			A[i] = B[x-p];
			i++;
			x++;
		}
		while (y <= right) {
			A[i] = B[y-p];
			i++;
			y++;
		}
	}
}

void output() {
	for (int i=1;i<n;i++)
		g<<A[i]<<' ';
	if (n > 0)
		g<<A[n]<<'\n';
	g.close();
}

int main() {

	read();
	sort(1, n);
	output();

	return 0;
}