Ok so I made what I believe is a counting sort. I first wrote it in Java just to test it, and it works there, but when I transferred it to CS50 IDE (of course, I modified it slightly to C syntax) it gives me segmentation error. After launching debug50 I noticed that pointing my cursor at temp array shows it's filled with junk data and not 0's like I expected. So I tried initializing it thusly: int temp[65536] = { 0 }; Didn't work. I tried making it static. Same thing. Even tried explicitly setting all its values to 0 with a for loop... The line that's highlighted by debugger is right below "if (temp[i] != 0)". Any hints would be appreciated.
void sort(int values[], int n)
{
// TODO: implement an O(n) sorting algorithm
if (n < 1)
{
printf("Array size n must be greater than 0.\n");
}
else
{
int temp[65536] = { 0 };
for (int i = 0; i < n; i++)
{
temp[values[i]] += 1;
}
for (int i = 0, j = 0; i < 65536; i++)
{
if (temp[i] != 0)
{
values[j] = i;
j++;
temp[i] -= 1;
i--;
}
if (j >= n)
{
break;
}
}
//return;
}
}