排序算法——基数排序

public class RadixSort {
public static void main(String[] args) {
int[] arr = new int[]{23,6,189,45,9,287,56,1,798,34,65,652,5};
radixSort(arr);
System.out.println(Arrays.toString(arr));
}

public static void radixSort(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();//将max加上空字符串,整体变为字符串,求得长度
    //创建二维数组用于临时存放按位分类的数据
    int[][] temp = new int[10][arr.length];
    //创建数组用于存放temp相应数组当中存放数据的个数
    int[] counts = new int[10];
    //最大数字的长度就是基数排序遍历的次数
    for (int i=0,n=1;i<maxLength;i++,n*=10){
        //遍历每一个数字
        for (int j=0;j<arr.length;j++){
            //计算余数
            int ys = arr[j]/n%10;
            //根据余数将当前值存入temp中对应的数组
            temp[ys][counts[ys]] = arr[j];
            //记录数量
            counts[ys]++;
        }
        //记录取出元素存放的位置
        int index = 0;
        //把数字取出来
        for (int k=0;k<counts.length;k++){
            //记录数量的数组中当前数值不为0
            if (counts[k]!=0){
                //循环取出元素
                for (int l=0;l<counts[k];l++){
                    //取出元素
                    arr[index] = temp[k][l];
                    index++;
                }
                //把记录数组数量置为0
                counts[k]=0;
            }
        }
    }
}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值