基数排序

基数排序详解

基数排序必须依赖另外的排序方法,最适合的是桶式排序。
基本思路:就是将待排序的数据拆分成多个排序关键字
采用最低位优先法
依次按照数据的拆分出来的个位、十位、百位。。。的子关键字排序。

实现代码

public class MultiKeyRadixSort
{
    public static void main(String[] args)
    {
        int[] data =
        { 1100, 192, 221, 12, 13 };
        System.out.println("排序之前:\n" + Arrays.toString(data));
        radixSort(data, 10, 4);
        System.out.println("排序之后:\n" + Arrays.toString(data));
    }

    public static void radixSort(int[] data, int radix, int d)
    {
        int arrayLength = data.length;
        // 临时数组
        int[] tmp = new int[arrayLength];
        // 桶式排序必须的数组
        int[] buckets = new int[radix];
        // 依次从最高位关键字对待排序数列排序
        // rate用于保存当前计算的位
        for (int i = 0, rate = 1; i < d; i++)
        {
            // 重置count数组
            Arrays.fill(buckets, 0);
            // 将data赋值到临时数组
            System.arraycopy(data, 0, tmp, 0, arrayLength);
            // 计算每个待排序的子关键字
            for (int j = 0; j < arrayLength; j++)
            {
                // 计算指定位上的子关键字
                int subKey = (tmp[j] / rate) % radix;
                buckets[subKey]++;
            }
            for (int j = 1; j < radix; j++)
            {
                buckets[j] = buckets[j] + buckets[j - 1];
            }
            // 按关键字对指定数据进行排序
            for (int m = arrayLength - 1; m >= 0; m--)
            {
                int subKey = (tmp[m] / rate) % radix;
                data[--buckets[subKey]] = tmp[m];
            }
            System.out.println("对" + rate + "位上的子关键字排序:"
                    + Arrays.toString(data));
            rate *= radix;
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值