Pagini recente » Cod sursa (job #236648) | Cod sursa (job #443753) | Cod sursa (job #2959150) | Cod sursa (job #646737) | Cod sursa (job #1040386)
#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;
}