// This file defines a class that represents arrays of integers // that can find their largest element. These objects are useful // as subjects of an experiment that compares two similarly // designed "max" algorithms, one of which seems to execute // faster than the other. // // The SlowMaxArray class provides the following to clients: // // o A constructor that takes the size of the array (n) as // its argument, and that initializes an array of n // elements with the integers n down to 1 (any array // in which the elements are in decreasing order like // this will be a worst case for the slow maximum-finding // algorithm). // // o findLargest, a message that returns the largest integer in // a section of an array. The parameter to this message // is the index of the last element in the section of // the array -- the section extends from position 0 up // to this position, inclusive. // History: // // October 2003 -- Adapted by Doug Baldwin from a similar class that // provided both the slow and fast maximum-finding algorithms. // Removed the fast algorithm. // // March 2003 -- Modified slightly (changes to message names, etc) // by Doug Baldwin, based on an original also by Doug Baldwin. // // October 2002 -- Original created by Doug Baldwin. class SlowMaxArray { // SlowMaxArrays store their elements in an ordinary array. They // also remember the number of elements they have: private int[] elements; private int size; // The constructor. This creates an array of the requested size // and fills it with the integers 1 through n. It also saves the // array's size in the appropriate member variable. public SlowMaxArray( int n ) { elements = new int[n]; for ( int i = 0; i < n; i++ ) { elements[i] = n - i; } size = n; } // The findLargest method. This is based on the recursive insight that // the maximum value in a one-element array is the only element in that // array. For an array with more than one element, compare the maximum // element in the front part of the array to the last element, and // return the last element if larger, otherwise recompute and return // the maximum element in the front part. public int findLargest( int lastIndex ) { if ( lastIndex > 0 ) { if ( elements[lastIndex] > this.findLargest( lastIndex-1 ) ) { return elements[lastIndex]; } else { return this.findLargest( lastIndex - 1 ); } } else { return elements[lastIndex]; } } }