snippetcsharpMinor
Counting sort review
Viewed 0 times
sortreviewcounting
Problem
I've just wrote a program in C# for counting sort.
I want reviews on my code and any better ways to implement this.
- space complexity is O(N+K)
- time complexity is O(N+K)
I want reviews on my code and any better ways to implement this.
namespace SortingSelfCoded
{
public static class CountingSorter
{
public static int[] CountingSort(int [] input)
{
// O(1)
int max = input[0];
// O(N)
for (int i = 0; i max)
{
max = input[i];
}
}
// Space complexity O(N+K)
int[] counts = new int[max + 1];
int[] output = new int[input.Length];
// O(N)
for (int i = 0; i 0)
{
output[j] = i;
j++;
counts[i]--;
}
}
return output;
}
}
}Solution
From a practical use point of view:
-
Consider changing your last while loop into a for loop. This avoids mutating the state of the
-
Even on a 64 bit system the size of an array is limited to 2GB. So if your largest key is in the vicinity of
- I'd use
input.Max()(LINQ) to obtain the maximum. Less code to write and does the same.
- While it is ok to use single letter variables for loop counter
jis not really a loop counter. It's the index of the current element so I would renamejintocurrentIndex.
-
Consider changing your last while loop into a for loop. This avoids mutating the state of the
count array (saves you a read and write on every iteration):for (int k = 0; k < count[i]; k++)
{
output[currentIndex++] = i;
}-
Even on a 64 bit system the size of an array is limited to 2GB. So if your largest key is in the vicinity of
Int32.Max / 4 or larger then you will get an OutOfMemoryException. Depending what else you are doing in your program you will get it much earlier. If you are experimenting around with sorting algorithms then there are some interesting approaches reducing the key space.Code Snippets
for (int k = 0; k < count[i]; k++)
{
output[currentIndex++] = i;
}Context
StackExchange Code Review Q#33135, answer score: 4
Revisions (0)
No revisions yet.