数据结构与算法【基础版】:3.9基数排序使用队列实现(优化)

3.9基数排序使用队列实现(优化)

思路:
  • 使用队列来排列不用计数
  • 只关心放进入,然后按照放进去的顺序取出来就可以了
代码:
package main.java.com.LiKou.arithmetic;

import main.java.com.LiKou.queue.MyQueue;

import java.util.Arrays;

/**
 * 将基数排序用队列优化
 */
public class RadixSortPlus {

    public static void main(String[] args) {

        int[] arr = new int[]{32, 21, 1, 7, 890, 784, 23, 5, 78, 33, 89, 98, 54, 33, 34,
                54, 53, 998,32, 21, 1, 7, 890, 784, 23, 5, 78, 33, 89, 98, 54, 33, 34,
                54, 53, 998,32, 21, 1, 7, 890, 784, 23, 5, 78, 33, 89, 98, 54, 33, 34,54, 53, 998};
        redixSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void redixSort(int[] arr){
        //存数组中最大的数字
        int max = Integer.MIN_VALUE;
        for(int i = 0; i < arr.length; i++){
            if(arr[i] > max){
                max = arr[i];
            }
        }
        //计算最大数字是几位数
        int maxLength = (max + "").length();    //数字+""就变成了字符串,就可以使用字符串的相应方法了
        //用于临时存储数据的队列数组
        MyQueue[] temp = new MyQueue[10];
        //为队列数组赋值,不然会报空指针异常
        for(int i = 0; i < temp.length; i++){
            temp[i] = new MyQueue();
        }
        //根据最大长度的数来决定比较的次数
        for(int i = 0, n = 1; i < maxLength; i++, n*=10){   //n用来求每轮对应的位数
            //把每一个数字分别计算余数
            for(int j = 0; j < arr.length; j++){
                //计算余数
                int ys = arr[j] / n % 10;
                //把当前遍历的数据放入指定的队列中
                temp[ys].add(arr[j]);
            }
            //记录取得元素需要放的位置
            int index = 0;
            //把所有队列中的数字取出来
            for(int k = 0; k < temp.length; k++){
                //当前遍历的队列不为空的时候,循环取
                while (!temp[k].isEmpty()){
                    //取出元素
                    arr[index] = temp[k].poll();
                    //记录下一个元素
                    index++;
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狂野小白兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值