Pre-Lab for Lab 0

Bubble Sort

Bubble sort is like selection sort, in that each iteration places the largest unsorted element into its correct place in the array. It differs from selection sort, however, in that each iteration also makes changes in the locations of the other elements in the array. The basic idea is that you start at the bottom of the array (element [0]) and compare successive pairs of elements, swapping whenever the bottom element is greater than the element above it. In this way, the largest element "bubbles" up toward the last array position. Now you have one array element in its correct position. Use the same technique in the next iteration to place the second largest element, and so on.

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.)