基數排序

基數排序

算法(遞歸實現):


package com.zq.algorithm.sort;

/**
 * Created by zhengshouzi on 2015/11/2.
 */
public class RadixSort {
    public static void main(String[] args) {
        int[] a = {135, 242, 192, 93, 345, 11, 24, 19};

        redixSort(a, 3, 1);

        System.out.println("最終結果:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(" " + a[i]);
        }
    }

    public static void redixSort(int[] a, int digit, int divide) {

        //遞歸退出條件,Math.pow()是API裏面求冪的函數,這裏是10的digit次方
        if (divide < Math.pow(10, digit)) {
            //基數
            int redix = 10;
            //一個零時數組,零時存放原來的數組,一個記錄桶信息,
            int[] temp = new int[a.length];
            int[] count = new int[redix];
            //這個循環就是生成每個桶需要記錄的信息
            for (int j = 0; j < a.length; j++) {
                //System.out.println(a[j]);
                int tempKey = a[j] / divide % redix;
                count[tempKey]++;
            }
            //這個循環是拷貝數組,當然API有自帶拷貝數組的API,爲了說明問題,就不用了。
            for (int i = 0; i < a.length; i++) {
                temp[i] = a[i];
            }
            ```下面的註釋是,一開始我沒有使用計數排序,自己拍腦袋想的方法```
            /*
            //定義一個變量,用來控制 a 數組下標
            int j = 0;
            //循環找到通過每一個基數排序後的順序,
            for (int k = 0; k < count.length; k++) {
                //如果存在基數對應的數,
                if (count[k] != 0) {
                    //遍歷temp數組,將和K值對應的那個數找出來,順序放入到 a 數組中,這樣就完成了 某一位上面的排序。
                    for (int l = 0; l < temp.length; l++) {
                        int tempKey = (temp[l] / divide) % redix;
                        if (tempKey == k) {
                            a[j++] = temp[l];
                        }
                    }
                }
            }*/

            for (int i = 1; i < redix; i++) {
                count [i] = count[i] + count[i-1];
            }
            //計數排序
            for (int i = a.length-1; i >= 0; i--) {
                int tempKey = (temp[i]/divide)%redix;
                count[tempKey]--;
                a[count[tempKey]] = temp[i];
            }
            /*
            for (int i = 0; i < count.length; i++) {
                System.out.print(" " + count[i]);
            }
            */
            System.out.println();
            System.out.print("對" + divide + "位計數排序後:");
            for (int i = 0; i < a.length; i++) {
                System.out.print(" " + a[i]);
            }
            System.out.println();
            //遞歸調用
            redixSort(a, digit, divide * 10);
        }


    }

}

排序結果

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