Java Program for Counting Sort

Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.





// Java implementation of Counting Sort
class CountingSort {
    void sort(char arr[])
        int n = arr.length;
        // The output character array that will have sorted arr
        char output[] = new char[n];
        // Create a count array to store count of inidividul
        // characters and initialize count array as 0
        int count[] = new int[256];
        for (int i = 0; i < 256; ++i)
            count[i] = 0;
        // store count of each character
        for (int i = 0; i < n; ++i)
        // Change count[i] so that count[i] now contains actual
        // position of this character in output array
        for (int i = 1; i <= 255; ++i)
            count[i] += count[i - 1];
        // Build the output character array
        for (int i = 0; i < n; ++i) {
            output[count[arr[i]] - 1] = arr[i];
        // Copy the output array to arr, so that arr now
        // contains sorted characters
        for (int i = 0; i < n; ++i)
            arr[i] = output[i];
    // Driver method
    public static void main(String args[])
        CountingSort ob = new CountingSort();
        char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o',
                      'r', 'g', 'e', 'e', 'k', 's' };
        System.out.print("Sorted character array is ");
        for (int i = 0; i < arr.length; ++i)
/*This code is contributed by Rajat Mishra */



Sorted character array is eeeefggkkorss

Please refer complete article on Counting Sort for more details!

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.