/* FILE: insertSort.cpp last change: 16-Mar-2001 author: Romeo Rizzi * This program reads a file of n unsorted integers and sorts them, * by iteratively assuming, for i := 1 to n-1, * that the first i elements are already sorted, * and searching for the right place where to insert element i+1. * The integers are put into a static array, * whose dimension is at most MAX_INTEGERS. */ #include #include const long int MAX_INTEGERS = 1000; main(int argc, char** argv) { if (argc < 2 || argc > 3) { cerr << "syntax:" << endl << " > insertsort " << endl << "or" << endl << " > insertsort " << endl << "where, = input file of unordered numbers" << endl << "and, = 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 = 2; i <= n; i++) { double new_comer = A[i]; long int j = i-1; while (j>0 && new_comer < A[j]) A[j+1] = A[j--]; A[j+1] = new_comer; } 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(); } }