一個有問題的基數排序(求解)

 

當要排序的數字量較大時(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;
        
    }
}

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