Here is a picture of a small array as it goes through one iteration of the outer loop of bubble sort:
++++++ ++++++ ++++++ ++++++ ++++++
[0] | 36 | | 24 | | 24 | | 24 | | 24 |
++++++ ++++++ ++++++ ++++++ ++++++
[1] | 24 | | 36 | | 36 | | 36 | | 36 |
++++++ ++++++ ++++++ ++++++ ++++++
[2] | 45 | | 45 | | 45 | | 6 | | 6 |
++++++ ++++++ ++++++ ++++++ ++++++
[3] | 6 | | 6 | | 6 | | 45 | | 12 |
++++++ ++++++ ++++++ ++++++ ++++++
[4] | 12 | | 12 | | 12 | | 12 | | 45 |
++++++ ++++++ ++++++ ++++++ ++++++
Note that in the process of placing the 45 in its correct location, the 6 and
12 have moved closer to their correct locations, and the 36 has moved
closer to its correct location.
We can start our design of bubble sort the same way we designed selection sort (refer to section 13.1 in the textbook):
for (i=n-1; i >= 0; --i)
put the next largest element in data[i]
Your job in lab tomorrow is to write the code for "put the next largest
element in data[i]". You should accomplish this by having the largest
element in the unsorted part of the array "bubble up" toward the top, causing
intermediate swaps as needed. (Hint: you should use a for-loop.)