数据结构----归并排序
原理:参考趣学数据结构
代码:
# include <stdio.h>
# include <stdlib.h>
# define N 100
void guiBingSort ( int a[ ] , int l, int h, int length) { int mid = ( l + h) / 2 ; int * b = ( int * ) malloc ( N* sizeof ( int ) ) ; int i = l, j = mid + 1 , k = 0 ; if ( i < j) { while ( i<= mid&& j<= h) { if ( a[ i] > a[ j] ) { b[ k++ ] = a[ j++ ] ; } else { b[ k++ ] = a[ i++ ] ; } } while ( i <= mid) { b[ k++ ] = a[ i++ ] ; } while ( j <= h) { b[ k++ ] = a[ j++ ] ; } } for ( i = l; i <= h; i++ ) { a[ i] = b[ i- l] ; } free ( b) ;
}
void fenZhi ( int a[ ] , int l, int h, int length) { if ( l < h) { int mid = ( l + h) / 2 ; fenZhi ( a, l, mid , length) ; fenZhi ( a, mid + 1 , h, length) ; guiBingSort ( a, l, h, length) ; }
}
void print8 ( int a[ ] , int length) { for ( int i = 0 ; i < length; i++ ) { printf ( "%d " , a[ i] ) ; } printf ( "\n" ) ;
}
int main ( ) { int a[ ] = { 1 , 4 , 6 , 7 , 4 , 3 , 2 , 11 , 5 , 7 , 8 , 9 , 6 , 55 } ; int length = sizeof ( a) / sizeof ( a[ 0 ] ) ; printf ( "排序前\n" ) ; print8 ( a, length) ; fenZhi ( a, 0 , length - 1 , length) ; printf ( "排序后\n" ) ; print8 ( a, length) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(n n),空间复杂度O(n) *
如果存在什么问题,欢迎批评指正!谢谢!