OJ6-3 C. radix sort

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

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值