|
//Date: 2003.09.08 //File: NOB_List02.cpp //Author: AOU #include <iostream.h> #include <stdlib.h> /* maintain an ordered list of integeres */ const int MAX_SIZE = 100; void display(int a[], int n); void initialize(int a[], int n); bool insert(int a[], int &n, int x); void swap(int &x, int &y); void main(void) { int values[MAX_SIZE]; initialize(values, MAX_SIZE); int n = 0; display(values, n); bool result = insert(values, n, 55); cout << result << endl; display(values, n); result = insert(values, n, 65); cout << result << endl; display(values, n); result = insert(values, n, 5); cout << result << endl; display(values, n); result = insert(values, n, 15); cout << result << endl; display(values, n); result = insert(values, n, -15); cout << result << endl; display(values, n); result = insert(values, n, -1); cout << result << endl; display(values, n); } void swap(int &x, int &y) { if (x != y) { int temp = x; x = y; y = temp; } } /* insert x in a[] Cases: if n = 0 then ... if n = MAX_SIZE then ... if n > 0 then a[n] = x n++ for i=n-1 to 1 step -1 if a[i] >= a[i-1] then get out of the for loop/function swap(a[i], a[i-1]) end for end if */ bool insert(int a[], int &n, int x) { if (0 == n) { a[n] = x; n++; return true; }; if (MAX_SIZE == n) return false; if (n > 0) { a[n] = x; n++; for (int i=n-1; i>=1; i--) { if (a[i] >= a[i-1]) return true; swap(a[i], a[i-1]); } } return false; } void initialize(int a[], int n) { for (int i=0; i<=n-1; i++) a[i] = 0; } void display(int a[], int n) { cout << "a[" << n << "]: "; for (int i=0; i<=n-1; i++) cout << a[i] << ' '; cout << endl; } |