Pagini recente » Cod sursa (job #461723) | Cod sursa (job #395502) | Cod sursa (job #1882858) | Cod sursa (job #2410833) | Cod sursa (job #1040391)
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NMax 500000
using namespace std;
int n, a[NMax], c[NMax];
void msort(int st, int dr);
void swap(int &a, int &b);
int main()
{
freopen("algsort.in", "r", stdin);
freopen("algsort.out","w", stdout);
int i;
scanf("%d", &n);
for (i=0; i<n; i++)
scanf("%d", &a[i]);
msort(0, n-1);
for (i=0; i<n; i++)
printf("%d ", a[i]);
printf("\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;
}