0

The array gets sorted inside the sort function but the haystack doesn't change. How do I pass haystack by reference without changing the function prototype?

void sort(int values[], int n)
{
  int count[MAX_VALUE] = { }; // initialise the range and result arrays
  int result[n];
  for(int i = 0; i < n; i++)
  {
    result[i] = 0;
    count[values[i]]++; // count the values array
  }
  for(int i = 1; i < MAX_VALUE; i++)
  {
    count[i] = count[i] + count[i-1]; // add consecutive elements in the count array
  }
  for(int i = 0; i < n; i++)
  {
    result[count[values[i]] - 1] = values[i];
    count[values[i]]--;
  }
  values = result;
  return;
}
0

Your problem is with the following line:

values = result;

You can not assign every value from one array into another with a simple one-line assignment like this. In order to change the array 'haystack', the sorted values from your result array need to be put back into the values array. You would probably need to use another for loop.

As an aside, you could also simplify this code, removing the cumulative counting, getting rid of the result array altogether and just assigning the sorted values straight back into values.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .