You are on page 1of 3

Counting Sort Algorithm

Step 1: Find the maximum element

In order to find the range of numbers in the array, we need to find the
maximum element in the array.

The best method to find the maximum element is by doing a linear traversal of
the array, and keep on updating the maximum value till that point.

Maximum element in input array

In the input array, we have max = 9 at index 8.

Time Complexity: O(n)

Space Complexity: O(1)

Step 2: Initialize a count array of length = (max + 1)

As we know our input array has a maximum value of 9, therefore, we know


there are only 10 possible values 0 to 9. We need to create a count array with
all possible values as indices and initialize each index with 0.

Initializi
ng Count Array

The next step must be to fill this count array.


Time Complexity: O(max)

Space Complexity: O(max)

Step 3: Fill the count array accordingly

In this step we have to fill the count array according to the frequencies present
in the input array.

The values of Count Array have filled as per the frequencies of the index in
the input array. For instance, there were three values of 5 in the input array,
therefore the Count Array has value 3 at index 5.

Time Complexity: O(n)

Space Complexity: O(1)

Step 4: Calculate cumulative frequency in Count Array

We need to find the cumulative frequencies of the Count Array. This will come
in handy later for sorting the input array.

Cumulative frequency is calculated by adding value at the current index with


the value at the previous index.

Calculating cumulative frequency

It must be noted that the last value of the cumulative array must be total
number of values present in the input array.
Note: To perform Counting Sort in descending order, we need to calculate
cumulative frequencies in reverse order. Everything besides this remains the
same.

Time Complexity: O(max)

Space Complexity: O(1)

Step 5: Fix the values in the sorted array

Using the cumulative count, we have somewhat the mapping for each element
present in the input array to its position in the sorted array.

We will pop values from the start of the input array, and place them according
to the value stored in the cumulative array.

Step 6: Printing the sorted array

The easiest part of the algorithm is printing the final sorted array.

Print the sorted array

Time Complexity: O(n)

Space Complexity: O(1)

You might also like