package chap08_Linear_Time_Sort; import static org.junit.Assert.*; import java.util.Arrays; import org.junit.Test; public class SortAlgorithms { /** * 计数排序算法 maxvalue为数组中的最大值 * * @param a * @param maxValue */ static void countingSort(int[] a, int maxValue) { // 制作a的副本 int[] b = Arrays.copyOf(a, a.length); // 创建包含从0到最大值maxvalue的数组,用于记录数组a中每个数字出现的次数 int[] c = new int[maxValue + 1]; // 记录次数 for (int i = 0; i < b.length; i++) { c[b[i]]++; } // 将c[i]表示小于i的数字的总数 for (int i = 1; i <= maxValue; i++) { c[i] += c[i - 1]; } // 将数组a中对应的位置填上相应的数字。仔细想想就好了,要从最后一个开始 for (int i = b.length - 1; i >= 0; i--) { a[c[b[i]] - 1] = b[i]; c[b[i]]--; } } @Test public void testName() throws Exception { int[] a = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 }; System.out.println(Arrays.toString(a)); countingSort(a, 21); System.out.println(Arrays.toString(a)); } }