# include # include using namespace std; int main ( ) // // INSERT_SORT demonstrates insertion sort. // // We start with an empty array (n = 0), and the user types // in, one after another, new integers to insert into the array. // { int a[100], b, i, in, n = 0, n_max = 100; cout << "\n"; cout << "This program demonstrates insertion sort.\n"; cout << "Enter, one at a time, another integer to insert.\n"; while ( n < n_max ) { // // Get the next item from the user. // Terminate if user hits CTRL-D. // cin >> b; if ( cin.eof ( ) ) { break; } // // Find the insertion point IN for the new item. // Guess it goes at the end (it's the biggest) but then // consider that it might be smaller than some entry. // in = n; for ( i = 0; i < n; i++ ) { if ( b < a[i] ) { in = i; break; } } // // Shift data up to make room at location IN. // for ( i = n - 1; in <= i; i-- ) { a[i+1] = a[i]; } a[in] = b; // // Update the count. // n = n + 1; // // Print the current array. // cout << "\n"; cout << "Current sorted array:\n"; cout << "\n"; for ( i = 0; i < n; i++ ) { cout << " " << a[i]; } cout << "\n"; } return 0; }