Counting Sort Algorithm in Java

Today, we are going to show the implementation of the Counting sort algorithm, which is the forth one from our series of tutorials on sorting algorithms. If you haven’t read the first three tutorials on BubbleSortInsertionSort and SelectionSort, I strongly recommend that you read them, because we will reuse code that was explained there.

The application is really simple, it will just get an instance of a Sortable algorithm, which in this case will be a CountingSort object and pass some Integer and String arrays to it, but unlike the other three algorithms that are able to sort any object that implements Comparable, this algorithm only works with Integers (positive and negative values), the arrays of String will be ignored. The last part of the code is to print the sorted arrays.

public class SorterApp {
  public static void main(String[] args) {
    SorterApp app = new SorterApp();;

  private void run() {
    sort(new Integer[] { 2, 42, -3, 2, 4 });
    sort(new Integer[] { 1, 2, 3, 4, 5 });
    sort(new Integer[] { 3, 1, 5, 4, 2 });
    sort(new Integer[] { 5, 4, 3, 2, 1 });


    sort(new String[] { "a", "b", "c", "d", "e" });
    sort(new String[] { "c", "a", "e", "d", "b" });
    sort(new String[] { "e", "d", "c", "b", "a" });

  private <T extends Comparable<T>> void sort(T[] values) {
    Sortable sorter = newSortable(4);
    // sorter.sortDescending(values);

  private Sortable newSortable(int sortableAlgorithm) {
    switch (sortableAlgorithm) {
      case 1:
        return new BubbleSort();
      case 2:
        return new InsertionSort();
      case 3:
        return new SelectionSort();
      case 4:
        return new CountingSort();
        return new BubbleSort();

You can see on the code below that the sortAscending and sortDescending invoke the same private method sort with the difference of 1 parameter. This is done because the code to sort in ascending or descending order is pretty much the same; the difference is just one small detail.

The Sorter Abstract class and the Sortable Interface were explained on the first tutorial of our series.

public class SelectionSort extends Sorter implements Sortable {
  public <T extends Comparable<T>> void sortAscending(T[] values) {
    sort(values, 0);

  public <T extends Comparable<T>> void sortDescending(T[] values) {
    sort(values, 1);

Because counting sort uses key values as indexes into an array, it is not a comparison sort algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence.

  private <T extends Comparable<T>> void sort(T[] values, int orderType) {
    if (!(values instanceof Integer[])) {
      System.out.println("Only Integer arrays can be sorted by the Counting Sort algorithm.");
    } else {
      // If the array is null or has the size of 1, it means it is already sorted.
      if ((null == values) || (values.length < 2)) {

      Integer[] temp = (Integer[]) values;
      int count = 0;
      int indexToInsertElement = 0;

      RangeElements rangeElements = Utils.getLowestAndHighestElement(temp);
      // The above method will iterate over all the elements in the array.
      count += temp.length;

      int lowestElement = rangeElements.getLowestElement();
      int highestElement = rangeElements.getHighestElement();
      // (highestElement - lowestElement) + 1 => It will be the possible range of the elements.
      int[] occurrences = new int[(highestElement - lowestElement) + 1];

      // Iterate through the array and count how many times each value has appeared and increment by
      // 1 every time.
      for (int i = 0; i < values.length; i++) {
        occurrences[temp[i] - lowestElement] += 1;

      // This peace of code is necessary just because we only want to create one method that will
      // sort ascending and descending, otherwise this code could be deleted.
      int currentIndex = 0;
      int finishIndex = 0;
      int increment = 0;
      if (0 == orderType) {
        // Ascending.
        currentIndex = 0;
        finishIndex = occurrences.length;
        increment = 1;
      } else if (1 == orderType) {
        // Descending.
        currentIndex = occurrences.length - 1;
        finishIndex = -1;
        increment = -1;

      while (currentIndex != finishIndex) {
        int nrOccurrences = occurrences[currentIndex];

        for (int j = 0; j < nrOccurrences; j++) {
          // It is necessary to "+ lowestElement" to compensate when it was subtracted.
          temp[indexToInsertElement++] = currentIndex + lowestElement;

        currentIndex += increment;

      System.out.printf("%2s: ", count);


Counting Sort Results

You can download all the files here: CountingSort.

Thank you for your time and feel free to leave any comments or questions.


3 thoughts on “Counting Sort Algorithm in Java”

  1. sir, I want to count “How many times the sorting technique goes and counts the number till the sorting is done “. I just want to know and advice me best site where I can find solution to my problem. I want to learn from the site.
    Because we were thought nothing our college life.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.