首页 > 编程语言 > 详细

基数排序

时间:2018-05-27 14:14:11      阅读:187      评论:0      收藏:0      [点我收藏+]
技术分享图片
 /**
     * 基数排序
     */
    @Test
    public void RadioSort(){
            int[] array = {123,345,5555,66666,764,12,33,455};
            int maxLength = maxLength(array);
            int[] newArray = sortCore(array,0,maxLength);
            System.out.println(Arrays.toString(newArray));
    }

    public int[] sortCore(int[] array,int dig,int maxLength){
        if(dig>=maxLength){
            return array;
        }
        final int radix=10;
        int arrayLength = array.length;
        int[] count=new int[radix];
        int[] bucket = new int[arrayLength];

        for(int i=0;i<array.length;i++){
            count[getDigit(array[i],dig)]++;
        }

        for (int i=1;i<radix;i++){
            count[i]=count[i]+count[i-1];
        }

        for (int i=arrayLength-1;i>=0;i--){
            int num=array[i];
            int d=getDigit(num,dig);
            bucket[count[d]-1]=num;
            count[d]--;
        }
        return sortCore(bucket,dig+1,maxLength);
    }

    public int maxLength(int[] array){
        int maxLength = 0;
        for (int i=0;i<array.length;i++){
            int currentLength =length(array[i]);
            if(maxLength<currentLength){
                maxLength=currentLength;
            }
        }
        return maxLength;
    }

    public int length(int num){
        return String.valueOf(num).length();
    }

    public  int getDigit(int x,int d){
        int[] a={ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
        return ((x/a[d])%10);
    }
View Code

 

基数排序

原文:https://www.cnblogs.com/nihaofenghao/p/9095888.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!