本文仅作原理的简单实现。代码中,使用链表来进行bucket的模拟较为妥当,如若下文一般,使用数组,需使用较多的ram(4 * 10 * size bytes)。原理分析,百度百科,各种博客,资源很多,不作赘述。
#include
#include
#define fatal_error(str) fprintf(stderr, "%s\n", str), exit(-1)
int nums[] = {64, 8, 216, 512, 27, 729, 0, 1, 343, 125};
int get_digit(int num, int base, int exponent)
{
int i, tmp;
tmp = 1;
for (i = 0; i < exponent; ++i)
{
tmp *= base;
}
return (num / tmp % base);
}
void radix_sort(int arr[], int size)
{
int exponent;
int digit;
int i, j, k;
// ten pointers in array, for 0 ~ 9
int *radix_array[10];
for (i = 0; i < 10; ++i)
{
// make one extra room for count
radix_array[i] = (int *)malloc(sizeof(int) * (size + 1));
if (radix_array[i] == NULL)
{
fatal_error("out of memory!");
}
radix_array[i][size] = 0;
}
for (exponent = 0; exponent < 10; ++exponent)
{
// arrange into radix_array
for (i = 0; i < size; ++i)
{
digit = get_digit(arr[i], 10, exponent);
j = radix_array[digit][size]++;
radix_array[digit][j] = arr[i];
}
// collect from radix_array
for (i = 0, k = 0; i < size; ++i)
{
for (j = 0; j < radix_array[i][size]; ++j)
{
arr[k++] = radix_array[i][j];
}
// reset count
radix_array[i][size] = 0;
}
}
for (i = 0; i < 10; ++i)
{
free(radix_array[i]);
}
}
int main()
{
radix_sort(nums, 10);
return 0;
}