I have a counting sort working as it should for x > 0, which sorts my array in a descending order. However the logic of my implementation falls apart when considering negative numbers, since I am reaching into negative indexes in the helper array values. I was thinking of somehow using uint but I am not very familiar with it.
How can I over come this Using a Counting Sort.
static void countingSort(int[] arr)
{
int i, j, max = -1; // I think it falls apart about here
int[] values;
for (i = 0; i < arr.Length; i++)
if (arr[i] > max) max = arr[i];
values = new int[max + 1];
//Here it reaches for a negative index when i = 2,looking for -6.
for (i = 0; i < arr.Max(); i++)
values[arr[i]]++;
i = 0; j = values.Length - 1;
while (i < arr.Length)
{
if (values[j] > 0)
{
values[j]--;
arr[i] = j;
i++;
}
else j--;
}
}
I know my problem is with the indexing of the helping array. And since I don't want to go on making arrays with negative indexes, I am a bit stumped.
Can you even do that in c# without implementing a whole class as a Indexer? I know you can do that in C, its well defined:
From C99 §6.5.2.1/2: The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).
My test array is { 8, 5, -6, 7, 1, 4 }
My expected output is { 8, 7, 5, 4, 1, -6 }