
/* selectionAll.cc -- Read an integer array, print it, then sort it and
 * print it. Use the selection sort method.
 */

#include <iostream.h>
#include <iomanip.h>

enum {NMAX = 10};

void printIntArray(int a[], int n)
     /* n is the number of elements in the array a.
      * These values are printed out, five per line. */
{
   for (int i = 0; i < n; ){
      cout << setw(10) << a[i++];
      if (i%5==0)
         cout << endl;
   }
   cout << endl;
}

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

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

void selectionSort(int a[], int n)
/* It sorts in non-decreasing order the first N positions of A. It uses 
 * the selection sort method.
 */
{
  for(int where, rh = n-1; rh > 0; rh--){
    //Elements in interval rh..n-1 are in their final position
    //Find position of largest element in range 0..rh
    where = 0;  // where is the position with the current maximum
    int temp;
    for (int lcv=1;lcv<=rh;lcv++)
      if (a[lcv]>a[where])
	where = lcv;
    temp = a[where];
    a[where] = a[rh];
    a[rh] = temp;
  }
}

void main(void) {
  int x[NMAX];
  int hmny;
  int who;
  int where;

  hmny = getIntArray(x, NMAX, 0);
  if (hmny==0)
     cout << "This is the empty array!\n";
  else{
     cout << "The array was: \n";
     printIntArray(x, hmny);
     selectionSort(x, hmny);
     cout << "The sorted array is: " << endl;
     printIntArray(x, hmny);
  }
}


