一个有问题的基数排序(求解)

 

当要排序的数字量较大时(1000+),随机数的范围比较小(1-100),排序后的数组会出现个别数字排序错误,

 

 

public class 基数排序 {

    public static void main(String[] args) {
        int[] e = new int[1000];
        for(int i = 0; i<e.length; i++) {
            e[i] = (int) (Math.random() * 100);
        }
        int[] sort = sort(e, 1, 1000);
        for (int i = 0; i < sort.length-1; i++) {
            if(sort[i]>sort[i+1]) {
                System.out.println(sort[i]);
            }
        }
    }
    
    /**
     * 排序
     * @param e    数组
     * @param a    个位数开始排序,(第一次传入为1)-->10-->100
     * @param max    数组中最大数(不知道就往大填)
     * @return    排序好的数组
     */
    public static int[] sort(int[] e, int a, int max) {
        int[][] bucket = new int[10][e.length];
        for(int i=0; i<e.length; i++) {
            int j = 0;
            while (bucket[(e[i])%(a*10)/a][j]!=0) {        //取个位数-->十位数-->百位数
                j++;
            }
            bucket[(e[i])%(a*10)/a][j] = e[i];
        }
        
        int x = 0;
        for(int i=0; i<10; i++) {
            int j = 0;
            while (bucket[i][j]!=0) {
                e[x] = bucket[i][j];
                x++;
                j++;
                if(j>=e.length) {        //当要排序的数组都去了二维数组中的某个数组,直接返回
                    return e;
                }
            }
        }
        if(a*10 < max) {                //当排序位数小于数组最大数,继续排
            return sort(e, a*10, max);
        }
        return e;
        
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章