I can implement different sortings, but I am meeting with sorting counting for the first time.

How to implement this algorithm? I can not run the counter

int nums[] = {1, 3, 1, 2, 4, 4, 3, 2, 3, 1}; int a[] = new int[10]; int count[] = new int[4]; int i, j; for (i = 0; i < 4; i++) { count[i] = 0; } for (j = 0; j < 10; j++) { count[nums[j]] = count[nums[j]] + 1; } 

    1 answer 1

    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; } } }