计数排序
| 4 | * 计数排序 |
| 5 | */ |
| 6 | public class CountingSort implements IArraySort { |
| 7 | |
| 8 | @Override |
| 9 | public int[] sort(int[] sourceArray) throws Exception { |
| 10 | // 对 arr 进行拷贝,不改变参数内容 |
| 11 | int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); |
| 12 | |
| 13 | int maxValue = getMaxValue(arr); |
| 14 | |
| 15 | return countingSort(arr, maxValue); |
| 16 | } |
| 17 | |
| 18 | private int[] countingSort(int[] arr, int maxValue) { |
| 19 | int bucketLen = maxValue + 1; |
| 20 | int[] bucket = new int[bucketLen]; |
| 21 | |
| 22 | for (int value : arr) { |
| 23 | bucket[value]++; |
| 24 | } |
| 25 | |
| 26 | int sortedIndex = 0; |
| 27 | for (int j = 0; j < bucketLen; j++) { |
| 28 | while (bucket[j] > 0) { |
| 29 | arr[sortedIndex++] = j; |
| 30 | bucket[j]--; |
| 31 | } |
| 32 | } |
| 33 | return arr; |
| 34 | } |
| 35 | |
| 36 | private int getMaxValue(int[] arr) { |
| 37 | int maxValue = arr[0]; |
| 38 | for (int value : arr) { |
| 39 | if (maxValue < value) { |
| 40 | maxValue = value; |
| 41 | } |
| 42 | } |
| 43 | return maxValue; |
| 44 | } |
| 45 | |
| 46 | } |
nothing calls this directly
no outgoing calls
no test coverage detected