#include <stdio.h>
#include <stdlib.h>
#define MAXLEN100
int a[MAXLEN];
void merg(int a[] , int b[] , size_t left , size_t mid , size_t right) {
int i , j , k;
for ( i = left , j = mid + 1 , k = 0 ;
i <= mid && j <= right ;
k++ ) {
if ( a[i] < a[j] )
b[k] = a[i++];
else
b[k] = a[j++];
}
while ( i <= mid )
b[k++] = a[i++];
while ( j <= right)
b[k++] = a[j++];
for ( i = left , k = 0 ; i <= right ; i++ , k++ )
a[i] = b[k];
}
void msort(int a[] , int b[] , size_t left , size_t right) {
if ( left < right ) {
size_t mid = (left + right) / 2;
msort(a , b , left , mid);
msort(a , b , mid + 1 , right);
merg(a , b , left , mid , right);
}
}
int main() {
int *b = malloc( MAXLEN * sizeof(int) );
if ( !b )
exit(EXIT_SUCCESS);
size_t len;
scanf("%u" , &len);
size_t i;
for ( i = 0 ; i < len ; i++ )
scanf("%d" , a + i);
msort(a , b , 0 , len - 1);
free(b);
for ( i = 0 ; i < len ; i++ )
printf("%d " , a[i]);
putchar('\n');
return 0;
}//此算法编程方式参考分治的版本
测试数据(两组,执行两次):
5 input
5 4 3 2 1
1 2 3 4 5 output
7 input
3 45 12 34 5 44 8
3 6 8 12 34 44 45 output