Is this a proper Count sort implementation?
Code and style improvements?
It does not support negative and that should be improved. A large input could cause out of memory.
Some of the array index is different as the WIKI is 1 based and these arrays are zero based.
public static void CountSort(int[] arr)
{
int max = -1;
foreach(int i in arr)
{
if (i < 0)
{
throw new IndexOutOfRangeException(" < 0 ");
}
max = Math.Max(max, i);
}
int n = arr.Length;
// The output character array that will have sorted arr
int[] output = new int[n];
// Create a count array to store count of inidividul
// characters and initialize count array as 0
int[] count = new int[max+1];
for (int i = 0; i <= max; ++i)
count[i] = 0;
// store count of each character
foreach (int i in arr)
count[i]++;
// Change count[i] so that count[i] now contains actual
// position of this character in output array
for (int i = 1; i <= max; ++i)
count[i] += count[i - 1];
// Build the output character array
for (int i = 0; i < n; ++i)
{
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
// Copy the output array to arr, so that arr now
// contains sorted characters
for (int i = 0; i < n; ++i)
arr[i] = output[i];
}
//test
int[] ar = new int[] { 0, 0, 0, 0 };
CountSort(ar);
foreach (int i in ar)
Debug.WriteLine(i);
Debug.WriteLine("");
ar = new int[] { 5, 5, 5, 5 };
CountSort(ar);
foreach (int i in ar)
Debug.WriteLine(i);
Debug.WriteLine("");
ar = new int[] {};
CountSort(ar);
foreach (int i in ar)
Debug.WriteLine(i);
Debug.WriteLine("");
ar = new int[] { 90, 90, 71, 82, 93, 75, 81, 0, 12, 54, 36, 13, 102, 99, 34, 103, 78, 196, 52, 5, 215 };
CountSort(ar);
foreach (int i in ar)
Debug.WriteLine(i);
Debug.WriteLine("");