zoukankan      html  css  js  c++  java
  • 基数排序

     /**
         * 基数排序
         */
        @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
  • 相关阅读:
    移位运算符
    java 链表数据结构
    log4j.properties配置详解
    java异常面试题
    QuickHit项目(输出字符串游戏)
    适配器模式
    java 单例
    sql索引的填充因子多少最好,填充因子的作用?
    聚焦索引和非聚焦索引的区别
    二叉树。。。。
  • 原文地址:https://www.cnblogs.com/nihaofenghao/p/9095888.html
Copyright © 2011-2022 走看看