Sorting by counting involves the creation of baskets (buckets), each of which stores the number of elements of the original array, the value of which coincides with the basket index. Accordingly, you need to have a basket, the indices of which will be from the minimum value of the array to the maximum.
When using an array to store baskets, indexes will be from 0 to X So that it was possible to work with negative numbers, and also not to store unnecessary values from 0 to the minimum value from the array, it makes sense to sort the minimum from all the elements of the array before sorting (or just before adding to the basket) from the basket) - add it back.
The result is:
public static void sort(int[] array) { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int element : array) { if (element < min) { min = element; } if (element > max) { max = element; } } int[] buckets = new int[max - min + 1]; for (int element : array) { buckets[element - min]++; } int arrayIndex = 0; for (int i = 0; i < buckets.length; i++) { for (int j = buckets[i]; j > 0; j--) { array[arrayIndex++] = i + min; } } }