swap function in lecture 5 and bubble sort

In lecture 5, David has explained that to actually have swap working, we actually need to point to the address of the string/char/int. However, when I look at my bubble sort code for helpers.c, I didn't do anything like that. I instead directly used for example:

``````if (int temp= values[g+1])
{
int temp=values[g];
values[g] =values[g+1];
values[g+1]= temp;
}
``````

And it worked. I am now confused because I expect it wouldn't change the values permanently. Any help is appreciated, thanks!

If you used the exact code that you posted, it will ALWAYS perform the swap, once you fix the double assignment (int temp) bug. Your condition is essentially `if( always true ) {do something}` Why is it always true? You performed an assignment `int temp = something` as your test condition. This will return true.

What you wanted to do is this:

``````int values[20];  // 20 or some other value
int g;
int tst;

// some more code in between that puts numbers in the values array and tst.
// and assigns something between 0 and 18 to g.

if ( tst == values[g+1])   // the test condition.
// note ^^ two equal signs to indicate a comparison. One "=" is assignment.
{
// swap values[g] with values[g+1]
int temp=values[g];
values[g] =values[g+1];
values[g+1]= temp;
}
``````

Your swap is essentially correct. With strings though, you have to make sure you are comparing and copying the strings, not the addresses of the strings. You would use functions like strcmp( stringa, stringb) or strcpy( stringa, stringb) to do this.

If you have more questions, please post them. When you feel that your question is answered, please mark this question as answered. Let's keep up on forum housekeeping. :-)