  /**
 * bubblesort.cpp
 * this program demonstrates the bubble sort algorithm.
 *
 */

#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;


// declare constants
const int NUM_DICE = 5;

// declare global variable
int dice[NUM_DICE];

// declare function prototypes
void initDice();
void printDice( int d[], int n );
void swapDice( int a, int b );
void bubbleSort();

/**
 * initDice()
 *
 * this function initializes the values in the array of dice to
 * integers between 1 and 6
 *
 */
void initDice() {
  for ( int i=0; i<NUM_DICE-1; i++ ) {
    dice[i] = ( rand() % 6 ) + 1;
  }
} // end of initDice()


/**
 * printDice()
 *
 * this function prints the values in the array of dice
 *
 */
void printDice( int d[], int n ) {
  int i;
  for ( i=0; i<n-1; i++ ) {
    cout << d[i] << " ";
  }
  cout << d[i] << endl;
} // end of printDice()



/**
 * swapDice()
 *
 * this function swaps two values in the array of dice
 *
 */
void swapDice( int a, int b ) {
  int tmp;
  tmp = dice[a];
  dice[a] = dice[b];
  dice[b] = tmp;
  return;
} // end of swapDice()



/**
 * bubbleSort()
 *
 * this function performs bubble sort.
 *
 */
void bubbleSort() {
  int num_passes = 0;
  for ( int pass=1; pass<NUM_DICE; pass++ ) {
    for ( int i=0; i<NUM_DICE-1; i++ ) {
      if ( dice[i] > dice[i+1] ) {
		swapDice( i, i+1 );
      }
    } // end for i
    num_passes++;
    cout << "after pass#" << num_passes << ": ";
    printDice( dice, NUM_DICE );
  } // end for pass
  cout << "TOTAL number of passes = " << num_passes << endl;
} // end of bubbleSort()



/**
 * main()
 *
 */
int main() {

  // initialize random number seed
  srand( time( NULL ));

  // initialize the array of dice
  initDice();

  // print the array before sorting it
  cout << "before sorting:";
  printDice( dice, NUM_DICE );

  // perform bubble sort
  bubbleSort();

  // print the array after sorting it
  cout << "after sorting:";
  printDice( dice, NUM_DICE );

} // end of main()
