next up previous
Next: Example: inverting the contents Up: Unit 07 Previous: Example: exhaustive search of

Example: search of the maximum element in an array of numbers

We develop a static method, maxArray(), which takes as parameter an array of integers and returns the maximum value in the array. We assume that the array contains at least one element. A possible realization is the following:

public static long maxArray(long[] v) {
  long max = v[0];
  for (int i = 1; i < v.length; i++)
    if (v[i] > max) max = v[i];
  return max;
}

Notice that the method uses a variable max to hold the current maximum while iterating over the elements of the array. The variable max is initialized to the value of the first element of the array, which by assumption must exist. Then max is updated whenever a bigger element is found. Hence, at the end of the loop, the value of max will coincide with the value of the maximum element of the array, and such a value is returned.

Example of usage:

public static void main(String[] args){
 long[] x = { 42, 97, 31, -25 };     // creation of an array x of 4 long
 System.out.println(maxArray(x));    // prints out 97
}


next up previous
Next: Example: inverting the contents Up: Unit 07 Previous: Example: exhaustive search of