Counting Sort Algorithm

Implementation in Java, an analysis of stability, parallelizability, and the Time and Space Complexities

Nickson Joram
Javarevisited
4 min readApr 17, 2021

--

We have seen sorting algorithms in the earlier article. Also, in the previous article, we have discussed the Counting Sort Algorithm.

In this article, we are going to see the implementation of the algorithm, analysis of stability, parallelizability, and the Time and Space Complexities of the Counting Sort Algorithm.

How to formulate the algorithm?

Implement the Counting Sort Algorithm in Java

What will be the output?

Another example

Time and Space Complexities

There are few numbers of for loops in this execution. Consider the for loops in the three phases of the execution.

Therefore, the overall time complexity = O(size)+O(max)+O(size) = O(max+size)

  1. Worst Case Complexity: O(max+size)
  2. Best Case Complexity: O(max+size)
  3. Average Case Complexity: O(max+size)

The complexity is the same in all of the preceding cases because the algorithm runs through max+size times regardless of how the elements are arranged in the array.

Counting Sort has a space complexity of O(max+size). The greater the range of elements, the greater the space complexity.

Stability of Counting Sort

The Counting Sort algorithm iterates from right to left over the input array while Writing Back Sorted Objects, copying objects with the same key from right to left into the output array. As a result, Counting Sort is a stable sorting algorithm.

Parallelizability of Counting Sort

Counting Sort can be parallelized by partitioning the input array into as many partitions as there are readily accessible processors.

Each processor counts the elements of “its” partition in a separate auxiliary array during Counting the Elements. During Aggregating the Histogram, all auxiliary arrays are incorporated together to form one. During Writing Back Sorted Objects, each processor copies “its” partition’s elements to the target array. The fields in the auxiliary array must be decremented and read atomically.

Because of parallelization, it is no longer possible to guarantee that elements with the same key are copied to the target array in the same order. As a result, the Parallel Counting Sort is not stable.

Hope the article can help. Share your thoughts too.

--

--