Search code examples
javasortingcounting-sort

Counting sort, why use cumulative


I went through the code of counting sort in many websites. They are using cumulative sum of count and then further array indexing. I meant to ask why aren't they using normal array printing:

As if [count of origArray(i) in count(origArray(i))!=0], loop through count(origArray(i)) and print i.

Is this because the main point of using Counting sort is NO COMPARISON, and there is a comparison with 0 in my code.

See this code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class CountingSort {
    public static void main(String... args) throws IOException {
        new CountingSort().sort();
    }

    private void sort() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        int max = 0;
        String data = "";
        while ((line = reader.readLine()) != null && line.length() != 0) {
            data += line;
        }
        String[] ip = data.split(" ");
        int[] intArray = new int[ip.length];
        for (int i = 0; i < ip.length; i++) {
            intArray[i] = Integer.parseInt(ip[i]);
            if (intArray[i] > max)
                max = intArray[i];
        }
        int[] count = new int[max+1];
        Arrays.fill(count, 0);
        for (int i = 0; i < intArray.length; i++) {
            ++count[intArray[i]];
        }
        for (int i = 0; i < max; i++) {
            if (count[i] != 0) {
                for (int j = 0; j < count[i]; j++)
                    System.out.print(" " + i);
            }
        }
    }

}

Solution

  • The implementations at the links that you share do not print System.out.print(" " + i) because they consider i different from the items being sorted. This would be true if you wanted to sort chars, because you would need a cast.

    Since you are using integers, there is nothing wrong with your implementation. In fact, you ended up with one of the variations of the algorithm mentioned on Wikipedia:

    If each item to be sorted is itself an integer, and used as key as well, then the second and third loops of counting sort can be combined; in the second loop, instead of computing the position where items with key i should be placed in the output, simply append Count[i] copies of the number i to the output.