Knowledge Base > Algorithm > Sorting
Overview
Counting Sort sorts in linear time by first knowing the range of the numbers(e.g. k) in the array A , and creating an array C of this length k. Each index in C is used to count how many elements in A are less than i, and the counts stored in C can be used to put corresponding element in A into the right position in the output array.
Algorithm
Pseudocode
|
The procedure is as follow:
Time Complexity
Counting sort has a running time of Θ(n + k), where n is the number of elements to be sorted and k is the range of those numbers. If k = O(n), this algorithm has Θ(n) performance.
Space Complexity
Counting sort does not sort in place, since it creates two other arrays, counting array C and output array. The space complexity is Θ(n + k), where n and k are the length of the array A and C, respectively. No swap operations is performed during the process.
Stability
Counting sort is stable. However, if you change the last for loop statement, ascending from 0 to SIZE -1, the result would be NOT stable.
Source Code