# 【基数排序（桶排序）】

/*

73, 22, 93, 43, 55, 14, 28, 65, 39, 81

0     1     2     3     4     5     6     7     8     9
81     22    43    14    55    65             28    39
93
73

81, 22, 73, 93, 43, 14, 55, 65, 28, 39

0     1     2     3     4     5     6     7     8     9
14    28     39    43    55    65    73    81    93
22

14, 22, 28, 39, 43, 55, 65, 73, 81, 93

LSD的基数排序适用于位数小的数列，如果位数多的话，使用MSD的效率会比较好，MSD的方式恰与LSD相反，是由高位数为基底开始

*/

#include<stdio.h>
#include<stdlib.h>

int main(void){
int data[10] = {73, 22, 93, 43, 55, 14, 28, 65, 39, 81};
int temp[10][10] = {0};
int order[10] = {0};
int i, j, k, n, lsd;
k = 0;
n = 1;
printf("\n排序前： ");
for(i = 0; i < 10; i++){
printf("%d ", data[i]);
}
putchar('\n');

while(n <= 10){
for(i = 0; i < 10; i++){
lsd = ((data[i] / n) % 10);
temp[lsd][order[lsd]] = data[i];
order[lsd]++;
}
printf("\n重新排列: ");

for(i = 0; i < 10; i++){
if(order[i] != 0){
for(j = 0; j < order[i]; j++){
data[k] = temp[i][j];
printf("%d ", data[k]);
k++;
}
}
order[i] = 0;
}
n *= 10;
k = 0;
}
putchar('\n');

printf("\n排序后: ");
for(i = 0; i < 10; i++){
printf("%d ", data[i]);
}
return 0;
}

posted @ 2017-02-12 22:48  天秤libra  阅读(512)  评论(0编辑  收藏