package wzs.sort;import java.util.Arrays;//計數排序//找出待排序的數組中最大和最小的元素//統計數組中每個值為i的元素出現的次數,存入數組C的第i項//對所有的計數累加(從C中的第一個元素開始,每一項和前一項相加)//反向填充目標數組:將每個元素i放在新數組的第C(i)項,每放一個元素就將C(i)減去1public class CountingSort{ public static void main(String[] argv) { int[] A = CountingSort.countingSort(new int[] { 10, 3, 5, 7, 9, 1, 4, 2, 6, 8 }); System.out.println(Arrays.toString(A)); } public static int[] countingSort(int[] A) { int[] B = new int[A.length]; // 假設A中的資料a'有,0<=a' && a' < k並且k=100 int k = 100; countingSort(A, B, k); return B; } private static void countingSort(int[] A, int[] B, int k) { int[] C = new int[k]; // 計數 for (int j = 0; j < A.length; j++) { int a = A[j]; C[a] += 1; } // 求計數和 for (int i = 1; i < k; i++) { C[i] = C[i] + C[i - 1]; } // 整理 for (int j = A.length - 1; j >= 0; j--) { int a = A[j]; B[C[a] - 1] = a; C[a] -= 1; } }}
輸出結果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]