Cod sursa(job #1040386)

Utilizator vladvlad00Vlad Teodorescu vladvlad00 Data 24 noiembrie 2013 14:47:13
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#define NMax 500000

using namespace std;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

int n, a[NMax], c[NMax];

void msort(int st, int dr);
void swap(int &a, int &b);

int main()
{
	int i;
	fin >> n ;

	for (i=0; i<n; i++)
		fin >> a[i];

	msort(0, n-1);

	for (i=0; i<n; i++)
		fout << a[i] << ' ';
	fout << "\n";
}

void msort(int st, int dr)
{
	int mij, x, y, z;

	if (st >= dr)
		return;

	if (st == dr-1)
	{
		if (a[st] > a[dr])
		{
			swap(a[st], a[dr]);
		}
		return;
	}
	
	mij = (st + dr) / 2;
	msort(st, mij);
	msort(mij+1, dr);

	// interclasare
	memset(c, 0, sizeof(c));

	z = 0;
	x = st;
	y = mij+1;

	while (x <= mij && y <= dr)
	{
		if (a[x] <= a[y])
			c[z++] = a[x++];
		if (a[x] > a[y])
			c[z++] = a[y++];
	}

	while (x <= mij)
		c[z++] = a[x++];

	while (y <= dr)
		c[z++] = a[y++];

	for (x=st, y=0; x<=dr; x++, y++)
		a[x] = c[y];
}

void swap(int &a, int &b)
{
	a = a ^ b;
	b = a ^ b;
	a = a ^ b;
}