# Pset3: why are the j and i values not swapping?

Here is my code:

`````` for(int i = 1; i < n - 1; i++) {
printf("%i\n %i\n", i, j);
int j = i + 1;
if(values[j] < values[i]) {
int tmp = j;
j = i;
i = tmp;
}
}
``````
• I have changed the swap so it is switching the arrays, but it still wont sort correctly Jun 24 '14 at 18:41

If you are trying to swap the values, you need to be using values[i] and values[j], not i and j.

• like i said to juan: good point but it still did not fix the problem. Jun 24 '14 at 5:16
• I'm assuming you are doing bubble sort? I've got pretty much identical code and it works fine for me (using values[i] and values[i+1] as the things being swapped). Perhaps your problem is somewhere else. Jun 24 '14 at 7:33

Do you mean:

``````if(values[j] < values[i]) {
int tmp = j;
j = i;
i = tmp;
}
``````

or

``````if(values[j] < values[i]) {
int tmp = values[j];
...
}
``````

?

And maybe values[j] is never less than values[i]

• good point but it still did not fix the problem. Jun 24 '14 at 3:22
• not necessarily. what about a random sequence of numbers users enter Jun 24 '14 at 8:16
• You are swapping i and j, and those are the indexes, not the values, the values are values[i] and values[j] Jun 24 '14 at 8:49
• it still wont sort correctly Jun 24 '14 at 18:40
• In your line of code printf("%i\n %i\n", i, j); what is the value of "j"? Because it is not initialized yet, is it? Jun 25 '14 at 13:02

Try replacing

``````if(values[j] < values[i])
{
int tmp = j;
j = i;
i = tmp;
}
``````

with

``````if(values[j]<values[i])
{
int tmp = values[j];
values[j] = values[i];
values[i] = tmp;
}
``````
• not sure what you mean. Jun 24 '14 at 18:39

found the fix!!!!!! it was only going through the numbers 1 time. I fixed it by adding:

``````for(int a = 0; a < n - 1; a++) {
``````

to the top (and putting a extra } at the end)

• The reason it wasn't working, and why this seemed to fix it, is because your original loop was only going through the array once. Adding this loop around the block of code makes it work, but its messy. You do not need 3 variables for the loop (i, j, and a). Jul 5 '14 at 20:56