import java.util.Random; import java.util.Arrays; class CountingSort { public static int[] sort(int[] A, int k) { int[] B = new int[A.length]; int[] C = new int[k]; // initialize counting array for (int i = 0; i < k; i++) { C[i] = 0; } // count instances of values stored in A[j] for (int j = 0; j < A.length; j++) { C[A[j]] += 1; } // produce cumulative totals in C so that // C[i] contains the number of elements <= i for (int i = 1; i < k; i++) { C[i] += C[i-1]; } // sort using position dictated by C[i] for (int j = A.length - 1; j >= 0; j--) { B[C[A[j]] - 1] = A[j]; // put A[j] in B in position C[A[j]] - 1 C[A[j]] = C[A[j]] - 1; // update count for C[A[j]] } return B; } public static void main(String[] args) { final int ARRSZ = 10; // size of array final int NUMNUMS = 10; // number of possible values Random r = new Random(); int[] A = new int[ARRSZ]; // populate array for (int j = 0; j < ARRSZ; j++) { A[j] = r.nextInt(NUMNUMS); } // sort int[] B = sort(A, NUMNUMS); // print System.out.println(Arrays.toString(A)); System.out.println(Arrays.toString(B)); } }