Ray Bell wrote:Thanks!
I changed it to this:
temp = myList[i + 1];
myList[i + 1] = myList[i];
myList[i] = temp;
It works perfectly now.
I'm still not sure how it works though.
Your first version didn't work because you used the wrong index in the third line of the swap. The bug was essentially restoring
myList[i] to what it was before the swap thus resulting in the values not being swapped. Despite that, you still set
changed to
true so the loop just kept going and going. I'm surprised you waited twenty minutes for it, given that you were only sorting ten numbers. You could have waited until all the cows came in and your sort would still not have been done.
If you think that declaring the temp variable outside of the loop is saving you something, it's not. Declare variables in the smallest scope possible. Not saying this cause the problem you saw but in general, declaring variables in a scope that's wider than their actual use is an invitation for bugs. Since
temp is used only inside the if-statement, that's where
you should declare it. It would have been better if you had written this instead:
Or you could follow Campbell's advice and create a utility method so you'd only have to write something like:
MyArrays.swap(myList, i, j)