public class CountingSort {

    public static void main(String[] args) {
        int[] array = new int[]{-5, 3, 9, 1, 6, 4, 10, 2, 8, 7, 15, 3, 2};

        System.out.println("Before: " + Arrays.toString(array));
        sort(array);
        System.out.println("After:  " + Arrays.toString(array));
    }

    public static void sort(int[] arr) {

        // This method is suitable for elements all distributed in a narrow range.

        int len = arr.length;

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;

        // sort out the min and max elements
        for (int i = 0; i < len; i++) {
            min = Math.min(min, arr[i]);
            max = Math.max(max, arr[i]);
        }

        // Since we get the min and max, we have the distribute range of elements in given array.
        // Then Instantiate an array of length (max-min+1) which is the range size of given elements.
        int[] buckets = new int[max - min + 1];
        Arrays.fill(buckets, 0);

        // Now, every element of different values are allocated a corresponding bucket.
        for (int i = 0; i < len; i++) {
            int bktId = arr[i] - min;
            buckets[bktId]++;
        }

        int count = 0;
        for (int i = 0; i < buckets.length; i++) {
            for (int j = 0; j < buckets[i]; j++) {
                arr[count++] = i + min;
            }
        }
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 14:51:02

results matching ""

    No results matching ""