radix_sort.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> //return the max number of a[] int find_max(int *a, int len) { int i, max = a[0]; for(i = 1;i < len;i++) { if(max < a[i]) max = a[i]; } return max; } //compute the digit cout of number int digit_cout(int number) { int cout = 0; do { number /= 10; cout++; }while(number != 0); return cout; } //return the kth digit of the number int kth_digit(int number, int kth) { number /= pow(10, kth); return (number % 10); } void radix_sort(int *a, int len) { int *temp[10]; int cout[10] = {0,0,0,0,0,0,0,0,0,0}; int max = find_max(a, len); int maxDigit = digit_cout(max); int i,j,k; //initialize the temp[][]. for(i = 0;i < 10;i++) { temp[i] = (int *)malloc(sizeof(int) * len); memset(temp[i], 0, sizeof(int) * len); } //do the maxDigit times for(i = 0;i < maxDigit;i++) { //每次装箱前把cout清空 memset(cout, 0, sizeof(int) * 10); for(j = 0;j < len;j++) { //将数据安装位数放入到暂存数组中 int xx = kth_digit(a[j], i); temp[xx][cout[xx]] = a[j]; //此箱子的计数递增 cout[xx]++; } int index = 0; //将数据从暂存数组中取回,放入原始数组中 for(j = 0;j < 10;j++) { //把箱子里所有的元素都取回到原始数组 for(k = 0;k < cout[j];k++) { a[index++] = temp[j][k]; } } } } void print_array(int *a, int len) { int i; for(i = 0;i < len;i++) { printf("%d ", a[i]); } printf("/n"); } int main() { int a[] = {22,32,19,67,12,6,89,64,36,99}; print_array(a, 10); radix_sort(a, 10); print_array(a, 10); return 0; }