Professional Documents
Culture Documents
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.
Time Complexity: O(n)
Space Complexity: O(1)
Initializi
ng Count Array
Space Complexity: O(max)
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)
We need to find the cumulative frequencies of the Count Array. This will come
in handy later for sorting the input array.
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)
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.
The easiest part of the algorithm is printing the final sorted array.
Time Complexity: O(n)
Space Complexity: O(1)