数据结构和算法(14)之基数排序

学习数据结构和算法的日常Demo

基数排序基本介绍

在这里插入图片描述

基数排序基本思想

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
代码实现:


public class 基数排序 {
    public static void main(String args[]) {
        int a[] = {6, 12, 32, 43, 8, 116, 221, 19, 77, 20};
        basicSort(a);
        System.out.println(Arrays.toString(a));
    }

    private static void basicSort(int[] a) {
        int max = a[0];
        for (int i = 1; i < a.length; i++) {
            if (max < a[i]) {
                max = a[i];
            }
        }
        int times = 0;
        while (max > 0) {
            max = max / 10;
            times++;        // 获取最大值的位数,得到基数排序的次数
        }
        List<ArrayList> queue = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ArrayList q = new ArrayList();
            queue.add(q);
            q = null;
        }
        for (int i = 0; i < times; i++) {
            for (int j = 0; j < a.length; j++) {
                // 获取对应位的值(i为0是个位,1是十位,2是百位)
                int x = a[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
                ArrayList q = queue.get(x); // {[0],[1],[2]...}
                q.add(a[j]);    // 添加进对应下标数组
                //queue.set(x,q);
            }
            // 开始收集
            int count = 0;
            for (int j = 0; j < 10; j++) {
                while (queue.get(j).size() > 0) {
                    ArrayList<Integer> q = queue.get(j);    //拿到每一个数组
                    a[count] = q.get(0);      //取出各个小数组中的元素,取一个删一个
                    q.remove(0);
                    count++;
                }
            }
        }
    }
}
GitHub:数据结构和算法源代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值