Counting sort is an integer sorting algorithm for a collection of objects that sorts according to the keys of the objects.
Steps
Example of Counting Sort
Auxiliary Space: O(n+k)
Time Complexity: Worst-case: O(n+k)
, Best-case: O(n)
, Average-case O(n+k)
Constraints:
Pseudocode:
for x in input:
count[key(x)] += 1
total = 0
for i in range(k):
oldCount = count[i]
count[i] = total
total += oldCount
for x in input:
output[count[key(x)]] = x
count[key(x)] += 1
return output
public class CountingSort
{
public static void SortCounting(int[] input, int min, int max)
{
var count = new int[max - min + 1];
var z = 0;
for (var i = 0; i < count.Length; i++)
count[i] = 0;
foreach (int i in input)
count[i - min]++;
for (var i = min; i <= max; i++)
{
while (count[i - min]-- > 0)
{
input[z] = i;
++z;
}
}
}
public static int[] Main(int[] input)
{
SortCounting(input, input.Min(), input.Max());
return input;
}
}