Pagini recente » Cod sursa (job #1083228) | Cod sursa (job #1929985) | Cod sursa (job #1502876) | Cod sursa (job #957582) | Cod sursa (job #1322874)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
const int nmax = 500000;
int v[nmax+1], v_aux[nmax+1];
void n2_sort( int x, int y ) {
for ( int i = x+1; i <= y; ++ i ) {
for ( int j = i; j > x; -- j ) {
if ( v[j] < v[j-1] ) {
int aux = v[j];
v[j] = v[j-1];
v[j-1] = aux;
}
}
}
}
void merge( int x, int y, int z ) {
int i = x, j = y;
for ( int ind = x; ind <= z; ++ ind ) {
if ( i >= y || ( j <= z && v[i] > v[j]) ) {
v_aux[ind] = v[j];
++ j;
} else {
v_aux[ind] = v[i];
++ i;
}
}
for ( int ind = x; ind <= z; ++ ind ) {
v[ind] = v_aux[ind];
}
}
int main( ) {
int n;
fin >> n;
for ( int i = 1; i <= n; ++ i ) {
fin >> v[i];
}
int nsqrt;
for ( nsqrt = 1; (nsqrt+1)*(nsqrt+1) <= n; ++ nsqrt ) {
}
for ( int i = 1; i <= nsqrt; ++ i ) {
n2_sort((i-1)*nsqrt+1,i*nsqrt);
}
if ( nsqrt*nsqrt<n ) {
n2_sort(nsqrt*nsqrt+1, n);
}
for ( int i = 2; i <= nsqrt; ++ i ) {
merge(1, (i-1)*nsqrt+1, i*nsqrt);
}
if ( nsqrt*nsqrt < n ) {
merge(1, nsqrt*nsqrt+1, n);
}
for ( int i = 1; i <= n; ++ i ) {
fout << v[i] << " ";
}
fout << "\n";
return 0;
}