基數排序


I. 計數排序

  1.  簡介:N 個在 0-k 之間的輸入元素排序,O(N) = N + k;

  2.  思想: 對於每個輸入元素 x,確定小於x的元素個數,直接將x插入到輸出數組的對應位置;

  3. 詳細代碼如下:

/**
 * Created by zf on 2017/12/13 0013.
 */
public class CountingSort {

    /**
     * 計數排序:對 n 個 0-k 之間數排序 O(n+k)
     * 對輸入的每個元素 x, 確定小於x的元素個數,然后直接將x放到輸出數組的對應位置
     *
     * @param k x的最大值
     * @param inputArray 輸入數組
     * @param outArray 輸出數組
     */
    public static void sort(int k, int[] inputArray, int[] outArray) {
        int[] temp = new int[k + 1];
        // 統計inputArray 中各元素個數
        for (int anInputArray : inputArray) {
            temp[anInputArray] = temp[anInputArray] + 1;
        }
        // 統計所有小於等於自己的元素個數
        for (int i = 1; i < temp.length; i++) {
            temp[i] = temp[i] + temp[i - 1];
        }
        //根據小於自己的元素個數,將元素直接放到輸出數組的對應位置
        for (int i = inputArray.length - 1; i >= 0; i--) {
            outArray[temp[inputArray[i]] - 1] = inputArray[i];
            temp[inputArray[i]] = temp[inputArray[i]] - 1;
        }
    }

    public static void main(String[] args) {
        int k = 100;
        int[] A = new int[]{13, 58, 2, 9, 79, 37, 97, 2, 36, 75, 64, 99, 100, 0, 0};
        int[] B = new int[A.length];
        sort(k, A, B);
        for (int i : B) {
            System.out.println(i);
        }
    }

}
View Code

 II. 基數排序

  1. 基本:

    a. 對給定的 n 個 d 位數,其中每一位都有k個可能的取值,從最低位開始,按位對n個數字進行穩定排序[相同時不會改變輸入輸出順序],

d次排序之后就能得到正確的排序;

    b. 假設每次按位使用穩定排序的時間復雜度為O(n)=(n+k)[計數排序],則該排序的O(n)=d(n+k);

  2. 擴展:

    a. 對給定 n 個 b 位數和任意整數 r<= b, 則可以將 每個關鍵字看做 d [d=b/r] 個 r 位數,則 r位數的每一位的最大值為 2r-1 [b的每一位為2進制數],則可使用 基數排序,其復雜度為 O(n) = (b/r)(n+2r-1);

    b. 例如對n個32位的數字排序, b=32, r=8, d=32/8=4; 則復雜度O(n) = 4 * (28 - 1 + n);

    c. 

    

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM