数据结构—基数排序
原理:参考趣学数据结构
代码:
# include <stdio.h>
# include <stdlib.h>
int getNumberBit ( int number) { int x = number, count= 0 ; if ( x == 0 ) return 1 ; while ( x != 0 ) { count++ ; x /= 10 ; } return count;
}
int getlongBit ( int a[ ] , int length) { int longBit = 0 ; for ( int i = 0 ; i < length; i++ ) { int tempBit = getNumberBit ( a[ i] ) ; if ( tempBit> longBit) { longBit = tempBit; } } return longBit;
}
int getNumberNoValue ( int number, int bit) { int value; while ( bit) { value = number % 10 ; number /= 10 ; bit-- ; } return value;
}
void jiShuSort ( int a[ ] , int length) { int * * b = ( int * * ) malloc ( 10 * sizeof ( int * ) ) ; int i; for ( i = 0 ; i < 10 ; i++ ) { b[ i] = ( int * ) malloc ( ( length + 1 ) * sizeof ( int ) ) ; b[ i] [ 0 ] = 0 ; } int longBit = getlongBit ( a, length) ; for ( int bit = 1 ; bit <= longBit; bit++ ) { for ( int i = 0 ; i < length; i++ ) { int tempV = getNumberNoValue ( a[ i] , bit) ; int index = ++ b[ tempV] [ 0 ] ; b[ tempV] [ index] = a[ i] ; } int k = 0 ; for ( int i = 0 ; i < 10 ; i++ ) { for ( int j = 1 ; j <= b[ i] [ 0 ] ; j++ ) { a[ k++ ] = b[ i] [ j] ; } b[ i] [ 0 ] = 0 ; } }
}
void print9 ( 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" ) ; print9 ( a, length) ; jiShuSort ( a, length) ; printf ( "排序后\n" ) ; print9 ( a, length) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(n x n),空间复杂度O(n x n)
如果存在什么问题,欢迎批评指正!谢谢!