

/* bubble.c -- Read an integer array, print it, then sort it and
 * print it. Use the bubble sort method.
 */

/* the program contains 3 functions namely 

  1. int getIntArray(int a[], int nmax);
 This function let user input (numbers not sorted) to be taken as an array a[]. 
 Here nmax is the number of user entries. Note nmax will not be allowed to be 
 greater than NMAX

  2. void bubbleSort(int a[], int n);
 This function sorts out the user enters numbers in an orderly fashion, 
 The entries in array a[] overwritten to reflect the acending order of the numbers
 entered

  3. void printIntArray(int a[], int n)
  This function prints out the the numbers

 NOTE: The function declerations:  
 int getIntArray(int a[], int nmax);
 void bubbleSort(int a[], int n);
 void printIntArray(int a[], int n);

  at the beginning of the program. This declaration of the functions at the 
  top enables the main() of the program to be 
  placed anywhere in the program. 

*/



#include <iostream.h>

#define NMAX 10

// note functions defined at the top here to ensure the 
//functions can reside anywhere in the .cpp file
int getIntArray(int a[], int nmax);
void bubbleSort(int a[], int n);
void printIntArray(int a[], int n);


int main(void) {
  int x[NMAX];
  int how_many;
 
  how_many = getIntArray(x, NMAX);
  if (how_many==0)
    cout << "This is the empty array!\n";
  else{
    cout <<"The array was: \n";
    printIntArray(x,how_many);
    bubbleSort(x,how_many);
    cout << "The sorted array is: \n";
    printIntArray(x,how_many);
  }

  return 0;
}



int getIntArray(int a[], int nmax)
     /* It reads up to nmax integers and stores then in a; sentinel 
      * terminates input. */
{
  int n = 0;
  int temp;

  do {
   cout <<"Enter integer [type 0 to terminate] ";
    cin >> temp;
    if (temp==0) break;
    if (n==nmax)
      cout << "array is full\n";
    else 
      a[n++] = temp;
  }while (1);
  return n;
}


void bubbleSort(int a[], int n)
/* It sorts in non-decreasing order the first N positions of A. It uses 
 * the bubble sort method.
 */
{
  int lcv;
  int limit = n-1;
  int temp;
  int lastChange;
  
  while (limit) {
    lastChange = 0;
    for (lcv=0;lcv<limit;lcv++)
      /* Notice that the values in positions LIMIT+1 .. N are in
       * their final position, i.e. they are sorted right */
	if (a[lcv]>a[lcv+1]) {
	  temp = a[lcv];
	  a[lcv] = a[lcv+1];
	  a[lcv+1] = temp;
	  lastChange = lcv;
	}
    limit = lastChange;
  }
}


void printIntArray(int a[], int n)
     /* n is the number of elements in the array a.
      * These values are printed out, five per line. */
{
  int i;

  for (i=0; i<n; ){
    cout << a[i++] << "\t";
    if (i%5==0)
      cout << endl;
  }
  cout << endl;
}

