C. radix sort
题目描述
radix sort
Given a sequence of numbers seperated by comma, you should sort them by radix sort.Output the step result of each pass
input
2 line
the first line is a sequence of numbers(<20) seperated by comma;the second is the step pass number(<5).
output
1 line
the sequence of the pass seperated by comma
#include <stdio.h>
void sort(int a[], int n, int exp);
int main()
{
int x = 0;
char y;
int a[20];
int top = -1;
while ((y = getchar()) != '\n')
{
if (y != ',')
{
x = x * 10 + y - '0';
}
else
{
a[++top] = x;
x = 0;
}
}
int n = top + 1;
int max = a[0];
for (int i = 1; i < n; i++)//是n不是10
if (max < a[i])
{
max = a[i];
}
}
int times = 0;
int k;
scanf("%d", &k);
for (int exp = 1; max / exp > 0; exp = exp * 10)
{
sort(a, n, exp);
times++;
if (times == k)
{
for (int j = 0; j < n; j++)
{
printf("%d,", a[j]);
}
}
}
return 0;
}
void sort(int a[], int n, int exp)
{
int bucket[10] = {0};
int output[n]; // 注意这里的大小
//统计每一个 最后一位的数字 分别有几个数
for (int i = 0; i < n; i++)
{
int last = (a[i] / exp) % 10;
bucket[last]++;
}
//累计,看最后一位数(包括自己)前面一个有多少的数
for (int i = 1; i < 10; i++)
{
bucket[i] = bucket[i] + bucket[i - 1];
}
//把数组中的数 映射到output
for (int i = n - 1; i >= 0; i--)
{
int index, last;
last = (a[i] / exp) % 10;
index = bucket[last] - 1;
output[index] = a[i];
bucket[last]--;
}
//把output 的数组弄到a
for (int i = 0; i < n; i++)
{
a[i] = output[i];
}
}
参考:https://www.cnblogs.com/skywang12345/p/3603669.html