I watched the Section video in week 3 which discussed Bubble sort. I also watched the lectures and the shorts on it. I understand how it works, except for one bit. I'm confused on the below image from the section (47.15 mins).

enter image description here

Specifically I am confused on two lines: 1) int swaps = 0. Why is this set to 0? Is that "true"? So does it mean that if the statement "there are no swaps" is true, then the program will run?

2) swaps++. So I guess here the swaps value is made into 1. And in the 2nd aray, it would become 2. What is the point of this?

Thank you.


The var swaps is used to detect whether any swaps occur, not to control whether the code displayed on the screen is allowed to run. Here's how it works. You want to know if any swaps ever occur. At the beginning, you set int swaps = 0; because so far, there have been no swaps. If at the end, it is still 0, then it means that no swaps were made and the list is sorted.

Now, when a swap occurs, the line swaps++; will be executed at the end of any individual swap. This increments swaps by 1. Since swap will be greater than 0, the list is still not sorted. (Actually it may or may not be sorted, but until you make a full pass with no swaps, there's no way to know.) As an extra benefit, the value of swaps will tell you how many swaps occurred on the pass.

So, after any pass thru the list, all you need to do is see if swaps != 0 to know that there was a swap, or that swap == 0 to know it is sorted.

If you have any more questions, please add them and we can expand on them.

If you are satisfied with the answer, please mark the question as answered. Let's keep up on forum housekeeping. ;-)

  • I feel like I am getting there, so here's some clarifying questions.
    – AU786
    Apr 20 '15 at 21:58
  • When the program is finished, will the value of the swaps be the quantity of the totals swaps made, or just the quantity of the swaps made in one iteration? From the image above, it seems that it is the quantity in one iteration.
    – AU786
    Apr 20 '15 at 22:04
  • Yes, swaps will only be the number of swaps on the latest iteration. Remember, the idea here is to track whether the latest pass has had no swaps. Also, you should know that when an int evaluates to 0, it would be treated as false. Any other integer value is considered true. So, when swaps is >0, ` !swaps ` evaluates to false, triggering another pass.
    – Cliff B
    Apr 20 '15 at 23:15

You must log in to answer this question.

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