1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| public class CountingSort { public static void main(String[] argv) { int[] A = CountingSort.countingSort(new int[]{16, 4, 10, 14, 7, 9, 3, 2, 8, 1}); Utils.print(A); }
public static int[] countingSort(int[] A) { int[] B = new int[A.length]; 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; } Utils.print(C); for (int i = 1; i < k; i++) { C[i] = C[i] + C[i - 1]; } Utils.print(C); for (int j = A.length - 1; j >= 0; j--) { int a = A[j]; B[C[a] - 1] = a; C[a] -= 1; } } }
public class CountSort{ public static void main(String []args){ int a[] = {100, 93, 97, 92, 96, 99, 92, 89, 93, 97, 90, 94, 92, 95}; int b[] = countSort(a); for(int i : b){ System.out.print(i + " "); } System.out.println(); } public static int[] countSort(int []a){ int b[] = new int[a.length]; int max = a[0], min = a[0]; for(int i : a){ if(i > max){ max = i; } if(i < min){ min = i; } } int k = max - min + 1; int c[] = new int[k]; for(int i = 0; i < a.length; ++i){ c[a[i]-min] += 1; } for(int i = 1; i < c.length; ++i){ c[i] = c[i] + c[i-1]; } for(int i = a.length-1; i >= 0; --i){ b[--c[a[i]-min]] = a[i]; } return b; } }
|