(七) 基数排序Java实现

12 篇文章 0 订阅

基数排序


核心:从元素的个位开始,按照数字放入0-19(不包含负数0-9)号桶,顺序取出,再按照倒数第二位排序


动图(不考虑负数)
在这里插入图片描述
代码(不考虑负数)

public static void radixSort(int[] arr) {
    // 二维数组模拟桶
    int[][] bucket = new int[10][arr.length];
    // 一维数组模拟索引
    int[] bucketCounts = new int[10];
    // 确定数组最大数的位数
    int max = arr[0];
    for (int n = 0; n < arr.length; n++) {
        if (arr[n] > arr[0]) {
            max = arr[n];
        }
    }
    int num = (max + "").length();
    for (int i = 0; i < num; i++) {
        for (int j = 0; j < arr.length; j++) {
            int digit = (int) ((arr[j] / Math.pow(10, i)) % 10);
            bucket[digit][bucketCounts[digit]] = arr[j];
            bucketCounts[digit]++;
        }
        int index = 0;
        for (int k = 0; k < bucketCounts.length; k++) {
            if (bucketCounts[k] != 0) {
                for (int l = 0; l < bucketCounts[k]; l++) {
                    arr[index++] = bucket[k][l];
                }
            }
            bucketCounts[k] = 0;
        }
    }
}

代码(考虑负数)

public static void radixSort(int[] arr) {
    int[][] bucket = new int[20][arr.length];
    int[] bucketCounts = new int[20];
    int max = arr[0];
    for (int n = 0; n < arr.length; n++) {
        if (arr[n] > arr[0]) {
            max = arr[n];
        }
    }
    int num = (max + "").length();
    for (int i = 0; i < num; i++) {
        for (int j = 0; j < arr.length; j++) {
            int digit = (int) ((arr[j] / Math.pow(10, i)) % 10)+10;
            bucket[digit][bucketCounts[digit]] = arr[j];
            bucketCounts[digit]++;
        }
        int index = 0;
        for (int k = 0; k < bucketCounts.length; k++) {
            if (bucketCounts[k] != 0) {
                for (int l = 0; l < bucketCounts[k]; l++) {
                    arr[index++] = bucket[k][l];
                }
            }
            bucketCounts[k] = 0;
        }
    }
}

本文动图来源:https://www.cnblogs.com/onepixel/p/7674659.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值