import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] arr = {4, 2, 7, 1, 3, 7, 9};
countingSort(arr);
System.out.println("排序后的数组: " + Arrays.toString(arr));
}
public static void countingSort(int[] arr) {
int min = Arrays.stream(arr).min().orElse(0);
int max = Arrays.stream(arr).max().orElse(0);
int range = max - min + 1;
int[] countArray = new int[range];
int[] sortedArray = new int[arr.length];
for (int value : arr) {
countArray[value - min]++;
}
for (int i = 1; i < range; i++) {
countArray[i] += countArray[i - 1];
}
for (int i = arr.length - 1; i >= 0; i--) {
int value = arr[i];
int index = countArray[value - min] - 1;
sortedArray[index] = value;
countArray[value - min]--;
}
System.arraycopy(sortedArray, 0, arr, 0, arr.length);
}
}