Counting Sort - Good
Counting Sort - Good
com
4-6 minutes
Sorting Algorithms
Counting sort
step 1
step 2
3. Store the count of each unique element of the input
array to the count array at their respective indices.
step 3
step 4
countingSort(inputArray, outputArray)
find the largest element in input array:- max
initialize the count array with all elements as zeros
for j = 0 to (size of input array -1)
find the total count of each unique element and
store the count at jth index in count array
for i = 0 to max
find the cumulative sum and store it in count array
itself
for j = (size-1) down to 0
copy the elements from the input array to the output
array
using the indices from count array.And each time an
element
is copied, decrement the corresponding count value.
Complexity Analysis:
Time Complexity:
There are five ‘for’ loops in the counting sort method. The
number of times these loops are executed are listed
below:
Space Complexity:
The space complexity of the Counting sort is O(n). The
larger the range of elements, the larger is the space
complexity.
It uses extra space for sorting the array elements (in this
case two arrays(counting and output arrays) are used),
hence it is not an In-place sorting algorithm.
That’s all for this article. Thank you for reading this article.
I hope, you have understood the Counting-sort algorithm
and its time and space complexities. You may read my
other useful articles on sorting data structure.