Common Array Algorithms
8. Finding the Maximum of an Array
Answer:
-20, 19, 1, 27, 5, -1, 27, 19, 5
- What is the maximum of the collection?
- 27
- How did you figure this out?
- By scanning over the integers left to right and mentally keeping track of the largest seen so far.
Finding the Maximum of an Array
A systematic procedure used to compute something is called an algorithm. The procedure described in the answer is an algorithm for finding the maximum of a list. An algorithm is a description of how to do something. It is not tied to any particular language. For example, you (possibly) followed the above algorithm when you mentally examined the list. An algorithm can be implemented in any computer programming language. The example program shows the above algorithm.
The variable max
plays the role of the largest integer seen so far. The program scans elements of the array starting at index 0 and going to the end.
The variable max
should be initialized to a value that is guaranteed to be no larger than the maximum element of the array. A program should always work correctly, regardless of the quirks of the data. Don't make assumptions
about what the data look like. (The initializer list is only for a convenience in this example. A typical program would get its data from the user or from a file.)
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 = ; // scan the array for ( int index=0; index < array.length; index++ ) { <more stuff goes here> } System.out.println("The maximum of this array is: " + max ); } } |
Question 8:
Fill in the blank so that
max
is initialized to a value that is guaranteed to be no larger than the maximum element of the array, no matter what values are in the initializer list.