八大排序算法之基数排序—Java

#基数排序
基数排序的求解思路可以参考链接.
此处只附对应的Java代码

public class RadixSortDemo {
    public static void main(String[] args) {
        int[] arr = {53, 3, 542, 748, 14, 214};
        radixSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void radixSort(int[] arr) {
        //1.先找到最大值
        int maxValue = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            maxValue = Math.max(maxValue, arr[i]);
        }
        //2.最大值对应几位数?
        int maxValueLength = (maxValue + "").length();
        //3.构建10个桶
        int[][] bucket = new int[10][arr.length];
        //4.每个桶中存放数据的个数
        int[] bucketElementCount = new int[10];
        //5.针对每个元素的对应位进行排序处理处理,第一次为个位,第二次为十位数...
        for (int i = 0, n = 1; i < maxValueLength; i++, n *= 10) {
            for (int j = 0; j < arr.length; j++) {
                //取出每个元素的对应位的值
                int digit = (arr[j] / n) % 10;
                bucket[digit][bucketElementCount[digit]++] = arr[j];
            }
            //6.按照桶的顺序将数据放入原数组
            int index = 0;
            for (int k = 0; k < bucketElementCount.length; k++) {
                for (int j = 0; j < bucketElementCount[k]; j++) {
                    arr[index++] = bucket[k][j];
                }
            }
            //7.重置bucketElementCount
            bucketElementCount = new int[10];
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值