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
| package org.coral.algorithm.sort;
public class CountSort implements Sort { public static void main(String[] args) { int[] numbers = {34, 12, 23, 56, 56, 56, 78}; CountSort countSort = new CountSort(); countSort.print(numbers); countSort.sort(numbers);
} @Override public void sort(int[] numbers) { int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE;
for(int i = 0; i < numbers.length; i++){ max = Math.max(max, numbers[i]); min = Math.min(min, numbers[i]); }
int[] help = new int[max - min + 1];
for(int i = 0; i < numbers.length; i++){ int mapPos = numbers[i] - min; help[mapPos]++; }
for(int i = 1; i < help.length; i++){ help[i] = help[i-1] + help[i]; }
int res[] = new int[numbers.length]; for(int i = 0; i < numbers.length; i++){ int post = --help[numbers[i] - min]; res[post] = numbers[i]; }
print(res); } }
|