#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define K 10 const int MAXN = 10000000; int N; int x[MAXN],y[MAXN]; void insert_sort(int a[],int l,int r) { int key; for (int i = l + 1; i <= r; i++) { key = a[i]; for (int j = i - 1; a[j] > key && j >= l; j--) a[j + 1] = a[j]; a[j + 1] = key; } } void merge(int a[],int l,int m,int r) { int n1 = m - l + 1; int n2 = r - m; int *t1,*t2; t1 = (int *)malloc(n1 * sizeof(int)); t2 = (int *)malloc(n2 * sizeof(int)); int i,j,k; for ( i = 0,k = l; i < n1; i++,k++) t1[i] = a[k]; for ( j = 0,k = m + 1; j < n2; j++,k++) t2[j] = a[k]; i = j = 0; for ( k = l; k <= r; k++) { if ( t1[i] <= t2[j] ) { a[k] = t1[i]; i++; if ( i == n1 ) { k++; for ( ; j < n2; j++,k++) a[k] = t2[j]; break; } } else { a[k] = t2[j]; j++; if ( j == n2 ) { k++; for ( ; i < n1; i++,k++) a[k] = t1[i]; break; } } } free(t1); free(t2); } void merge_sort1(int a[],int l,int r) { if ( r - l + 1 <= K ) { insert_sort(a,l,r); return; } int mid = ( l + r ) / 2; merge_sort1(a,l,mid); merge_sort1(a,mid + 1,r); merge(a,l,mid,r); } void merge_sort2(int a[],int l,int r) { if ( l < r ) { int mid = ( l + r ) / 2; merge_sort2(a,l,mid); merge_sort2(a,mid + 1,r); merge(a,l,mid,r); } } int main() { srand(time(NULL)); scanf("%d",&N); for (int i = 0; i < N - 1; i++) { x[i] = rand() % 100000; y[i] = x[i]; } int begin = clock(); merge_sort1(x,0,N - 1); int end = clock(); printf("insert & merge : total time of sorting : %lf\n",(double)( end - begin ) / CLOCKS_PER_SEC); begin = clock(); merge_sort2(y,0,N - 1); end = clock(); printf("merge : total time of sorting : %lf\n",(double)( end - begin ) / CLOCKS_PER_SEC); return 0; }