#include<stdio.h>
#define MAX 20
#define SHOWPASS
#define BASE 10
void print(int *a, int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d\t", a[i]);
}
}
void radixsort(int *a, int n) {
int i, b[MAX], m = a[0], exp = 1;
//找出最大值
for (i = 1; i < n; i++) {
if (a[i] > m) {
//令 m 为最大值
m = a[i];
}
}
// 最大值 m ÷ exp 得到运行次数,exp:1 每次乘10
// m:99,99/1>0,99/10>0,99/100=0
while (m / exp > 0) {
int bucket[BASE] = { 0 };
//执行while第一次,for 执行结束后,将标出所有相同个位的总数在buctet中
//a{50,123,543,187,49,30,0,2,11,100}; bucket{4,1,1,2,0,0,0,1,0,1}
for (i = 0; i < n; i++) {
bucket[(a[i] / exp) % BASE]++;
}
//目的???
//bucket{4,5,6,8,8,8,8,9,9,10}
for (i = 1; i < BASE; i++) {
bucket[i] += bucket[i - 1];
}
//目的???
//bucket{0,4,5,6,8,8,8,8,9,9}
//执行while第一次,按个位进行分配 b{50,30,0,100,11,2,123,543,187,49}
for (i = n - 1; i >= 0; i--) {
b[--bucket[(a[i] / exp) % BASE]] = a[i];
}
//保存每次基数排序的结果
for (i = 0; i < n; i++) {
a[i] = b[i];
}
exp *= BASE;
#ifdef SHOWPASS
printf("\nPASS : ");
print(a, n);
#endif
}
}
int main() {
int arr[MAX];
int i, n;
printf("Enter total elements (n <= %d) : ", MAX);
scanf_s("%d", &n);
n = n < MAX ? n : MAX;
printf("Enter %d Elements : ", n);
for (i = 0; i < n; i++) {
scanf_s("%d", &arr[i]);
}
printf("\nARRAY : ");
print(&arr[0], n);
radixsort(&arr[0], n);
return 0;
}