编辑代码

import java.util.Arrays;

public class CountingSort {

    public static void countingSort(int[] arr) {
        int max = getMax(arr);
        int[] count = new int[max + 1];

        // 计数
        for (int value : arr) {
            count[value]++;
        }

        // 累加计数
        for (int i = 1; i <= max; i++) {
            count[i] += count[i - 1];
        }

        // 输出到结果数组
        int[] result = new int[arr.length];
        for (int i = arr.length - 1; i >= 0; i--) {
            result[count[arr[i]] - 1] = arr[i];
            count[arr[i]]--;
        }

        // 将结果复制回原数组
        System.arraycopy(result, 0, arr, 0, arr.length);
    }

    private static int getMax(int[] arr) {
        int max = arr[0];
        for (int value : arr) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }

    public static void main(String[] args) {
        int[] arr = {4, 2, 2, 8, 3, 3, 1};
        countingSort(arr);
        System.out.println("计数排序后: " + Arrays.toString(arr));
    }
}