zoukankan      html  css  js  c++  java
  • Radix_Sort

    public class Radix_sort {
        
        public static void  sort(int[] arrays,int radix){
            
            int n = 1;
            int length = arrays.length;
            int[][] bucket = new int[10][length]; //保存根据元素某个位数上的数字的分组结果
            int[] count=new int[length]; //用来存储每个数字的个数
            int flag = 0; //判断排序是否结束
            
            Arrays.fill(count, 0); //初始化count为0
            
            while(flag < length){
                
                flag = 0 ;//每次排序前置0
                for(int i = 0; i < length; i++){
                    int index = (arrays[i] / n)% radix; //取该元素n位数上的数字
                    
                    bucket[index][count[index]++] = arrays[i];  //将该元素保存到对应的数组
                    
                    if(arrays[i] / n == 0){  //如果元素除以n 为0 代表该元素的每位数已经排完序
                        flag ++;
                    }
                }
                
                int num = 0;
                for(int i = 0; i < 10; i++){
                    for(int j = 0; j < count[i]; j++){ //将分组结果重新保存到原数组中 新的数组已经按照每个元素的 某位数进行了排序
                        arrays[num++] = bucket[i][j];
                    }
                    count[i] = 0; //将每个分组的统计个数置为0
                }
                n *= 10; //位数向前移一位
            }
        }
        
        public static void main(String[] args){
            int[] A=new int[]{300,222, 8875, 60, 104110, 14, 5555, 30, 77754, 45, 105131};
            
            sort(A, 10);
            for(int num:A)
            {
                System.out.println(num);
            }
        }
    }
  • 相关阅读:
    Linux常用命令大全(非常全!!!)
    洛谷 P3379 【模板】最近公共祖先(LCA)
    POJ 3259 Wormholes
    POJ 1275 Cashier Employment
    POJ 3169 Layout
    POJ 1201 Intervals
    洛谷 P5960 【模板】差分约束算法
    洛谷 P3275 [SCOI2011]糖果
    POJ 2949 Word Rings
    POJ 3621 Sightseeing Cows
  • 原文地址:https://www.cnblogs.com/sirhuoshan/p/3479235.html
Copyright © 2011-2022 走看看