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

const int MAX = 5;
int x[MAX];
void swap(int, int);
void init_vals();
void b_sort();
void print_vals();

/*
 * an implementation of bubble sort
 */
void b_sort() {
  for (int i = 0; i < MAX-1; i++) {
    for (int i = 0; i < MAX-1; i++) {
      if (x[i] > x[i+1]) 
        swap(i,i+1);
    }
  } // end outer for  
  return;
}

/*
 * helper function to b_sort
 */
void swap(int pos1, int pos2) {
  int temp;
  temp = x[pos1];
  x[pos1] = x[pos2];
  x[pos2] = temp;
  return;
}

/*
 * initializes values of array x
 */
void init_vals() {
  for (int i = 0; i < MAX; i++)
    x[i] = rand()%MAX;
  return;
}

/*
 * prints values of array x
 */
void print_vals() {
  for (int i = 0; i < MAX; i++)
    cout << x[i] << " ";
  cout << endl;
  return;
}

/*
 * main thread demonstrates bubble sort
 */
int main() {
  srand(time(NULL));
  init_vals();
  cout << "\nbefore sort: " << endl;
  print_vals();
  b_sort();
  cout << "after sort: " << endl;
  print_vals();
  cout << endl;
  
  return 0;
}

