Source of bubbleSort.cpp


  1: //  Created by Frank M. Carrano and Tim Henry.
  2: //  Copyright (c) 2013 __Pearson Education__. All rights reserved.

  4: // Listing 11-2.

  6: #include <iostream>
  7: #include <string>

  9: using namespace std;
 10: template<class ItemType>

 12: /** Sorts the items in an array into ascending order.
 13:  @pre  None.
 14:  @post  theArray is sorted into ascending order; n is unchanged.
 15:  @param theArray  The given array.
 16:  @param n  The size of theArray. */
 17: void bubbleSort(ItemType theArray[], int n)
 18: {
 19:    bool sorted = false; // False when swaps occur
 20:    int pass = 1;
 21:    while (!sorted && (pass < n))
 22:    {
 23:       // At this point, theArray[n+1-pass..n-1] is sorted
 24:       // and all of its entries are > the entries in theArray[0..n-pass]
 25:       sorted = true; // Assume sorted
 26:       for (int index = 0; index < n - pass; index++)
 27:       {
 28:          // At this point, all entries in theArray[0..index-1]
 29:          // are <= theArray[index]
 30:          int nextIndex = index + 1;
 31:          if (theArray[index] > theArray[nextIndex])
 32:          {
 33:             // Exchange entries
 34:             std::swap(theArray[index], theArray[nextIndex]);
 35:             sorted = false; // Signal exchange
 36:          } // end if
 37:       }  // end for
 38:       // Assertion: theArray[0..n-pass-1] < theArray[n-pass]
 39:       
 40:       pass++;
 41:    }  // end while
 42: }  // end bubbleSort

 44: int main()
 45: {
 46:    string a[6] = {"Z", "X", "R", "K", "F", "B"};
 47:    bubbleSort(a, 6);
 48:    for (int i = 0; i < 6; i++)
 49:       cout << a[i] << " ";
 50:    cout << endl;   
 51: }  // end main

 53: /*

 55:  B F K R X Z 
 56:  
 57: */