(Latest Revision: 02/24/2004)

Bubble Sort



// Assumes DataType has been defined



void bubbleSort(DataType theArray[], int n)

// ---------------------------------------------------
// Sorts the items in an array into ascending order.
// Precondition: theArray is an array of n items.
// Postcondition: theArray is sorted into ascending
// order; n is unchanged.
// Calls: swap.
// ---------------------------------------------------

{

   bool sorted = false; // false when swaps occur

/* This loop iterates up to n-1 times (worst case) */

   for (int pass = 1; (pass < n) && !sorted; ++pass)
   {  // Invariant: theArray[n+1-pass..n-1] is sorted
      // and > theArray[0..n-pass]
      sorted = true; // assume sorted

/* This loop iterates up to n-pass times (worst case) - 'pass' starts at 1 and
   increments as high as n-1 in the worst case. In the worst case one swap and
   one comparison is performed in each iteration.  Therefore in the worst case
   bubble sort performs (n-1)+(n-2)+(n-3)+ ... + 2+1 = n(n-1)/2 comparisons
   and swaps. 
*/

    for (int index = 0; index < n-pass; ++index)
      {  // Invariant: theArray[0..index-1] <=
         // theArray[index]
         int nextIndex = index + 1;
               
         if (theArray[index] > theArray[nextIndex])
         {  // exchange items
            swap(theArray[index], theArray[nextIndex]);
            sorted = false; // signal exchange
         } // end if
      } // end for
      // Assertion: theArray[0..n-pass-1] <
      // theArray[n-pass]
   } // end for
} // end bubbleSort