/* FILE: minSort.cpp   last change: 16-Mar-2001   author: Romeo Rizzi
 * This program reads a file of n unsorted integers and sorts them,
 * by repeatedly looking for a smallest element to put in front
 * of the others.
 * The integers are put into a static array,
 * whose dimension is at most MAX_INTEGERS.
 */

#include <fstream.h>
#include <iostream.h>

const long int  MAX_INTEGERS = 1000;

main(int argc, char** argv) {
  if (argc < 2 || argc > 3) {
     cerr << "syntax:" << endl
          << " > minsort <file1>" << endl
          << "or" << endl
          << " > minsort <file1> <file2>" << endl
          << "where, <file1> = input file of unordered numbers" << endl
          << "and, <file2> = output sorted file" << endl;
     exit(1);
  }

  ifstream  in;
  in.open(argv[1]);
  if (!in.good()) {
     cerr << "err: file " << argv[1] << " does not exist" << endl;
     exit(1);
  }

  double A[MAX_INTEGERS+1];
  long int n = 0;
  do {
     in >> A[++n];
     if (n > MAX_INTEGERS) {
        cerr << "err: file " << argv[1] << " contains more than "
             << MAX_INTEGERS << " integers." << endl;
        exit(1);
     }
  } while (!in.eof());
  in.close();

  for(long int i = 1; i < n; i++) {
     double min = A[i]; long int pos_min = i;
     for (long int j = i+1; j <= n; j++)
       if (A[j] < min) {
           min = A[j];
           pos_min = j;
       }
     double swap = A[i];    // begin: swap  A[i] and A[pos_min]
     A[i] = A[pos_min];
     A[pos_min] = swap;     // end: swap  A[i] and A[pos_min]
  }

  if (argc == 2)  for(long int i = 1; i <= n; i++)  cout << A[i] << endl;
  else {
     ofstream  out;
     out.open(argv[2]);
     if (!out.good()) {
        cerr << "err: could not open file " << argv[2] << endl;
        exit(1);
     }
     for(long int i = 1; i <= n; i++)  out << A[i] << endl;
     out.close();
  }
}

