基数排序简单示例
/*基数排序又称桶排序,原理是按照每一位分别进行排序,时间复杂度较低,适用于顺序和链式存储结构*/
#include <stdio.h>
#define D 2 //最大位数
#define N 7 //数据个数
int main ()
{
int buk[10][N] = { 0 };//存放按一位排序后数据的桶
int in_len[10] = { 0 };//存放按位放到桶中的数,每一位分别有多少个
int data[N] = { 15, 8, 21, 19, 30, 5, 0 };
int i, j, k, m, n;
int lsb;
lsb = i = j = k = m = n = 0;
for (i = 0; i < N; i++)
printf ("%d ", data[i]);
printf ("\n");
for (i=0, n = 1; i < D; i++, n *= 10)
{
for (j = 0; j < 10; j++)
in_len[j] = 0;
m = 0;//用于从桶中放回时的下标
for (j = 0; j < N; j++)
{
lsb = data[j] / n % 10;
buk[lsb][in_len[lsb]++] = data[j];
}
for (j = 0; j < 10; j++)
{
for (k = 0; k < in_len[j]; k++)
{
data[m++] = buk[j][k];
}
}
}
for (i = 0; i < N; i++)
printf ("%d ", data[i]);
printf ("\n");
return 0;
}