0

So I am working on Selection Sort for Find, Problem Set 3. When I use a function I made called swap to exchange the values, the array is not sorted. Function snippet:

if (min != i)
{
    swap(values[i], values[min];
}


void swap(int a, int b)
{
     int tmp = a;
     a = b;
     b = temp;
}

However when I remove the function and use code instead of the function, the array sorts. Snippet below:

if (min != i)
{
    // swap value of i and with the minimum value.
    int temp = values[i];
    values[i] = values[min];
    values[min] = temp;
}

Any idea why is this happening?

2
  • I don't know if this is a typo or not but you forgot to include the ) at the end of swap(values[i], values[min];. Could you also include the outcome/errors that the code gives? – SuperNovaCoder Feb 26 '17 at 20:01
  • Nope thats just a typo. Also realised what the problem was. See my answer below. – Satanic Saint Feb 26 '17 at 20:13
2

C, by default, passes parameters to functions by value. That means when the function swap is called, two new variables, x and y are created, and the values of the integers are copied into them. When the function returns, the two variables x and y cease to exist. The original data in my calling function is unchanged. This is covered in Week 2 shorts and the Week 4 Lecture. I totally forgot about this. So yeah, my bad. Nothing to see here. Move on.

You must log in to answer this question.

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