Common Array Algorithms
9. Classic Bug (1): Initializing Max Incorrectly
Answer:
The first (index 0) element in an array will never be larger than the maximum element in that array. (It might be the maximum element of the array; but this is fine.)
max = array[0];
This code assumes that there is at least one element in the array. If there is not, the java system will detect that the index "0" is out of bounds and throw an exception.
Classic Bug (1): Initializing Max Incorrectly
Classic Bug (1): It is tempting to initialize max
to something you think is much less than the maximum, like -999. However, in doing so you make a risky assumption about the data. Perhaps the array holds the national debt for each of the last ten years. All these values are negative, and -999 would easily exceed the true maximum.
Examine the program. Notice how max
is initialized to the first element in the array (at index 0). This assumes that the array exists and that it has at least one element. For the present program this is a safe assumption (but might not be in other situations.)
The for
loop is set up to look at every element in the array, starting with the first element in cell 0, to see if that element is larger than the current maximum.
It would be OK (and perhaps preferable) to start out index
at 1 since index 0 was used to initialize max
. But the program as written works fine (as soon as you fill in the blank).
class MaxAlgorithm { public static void main ( String[] args ) { int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ; int max; // initialize the current maximum max = array[0]; // scan the array for ( int index=0; index < array.length; index++ ) { if ( ) // examine the current element max = array[ index ]; // if it is the largest so far, change max } System.out.println("The maximum of this array is: " + max ); } } |
Question 9:
Complete the program.