Source of IntegerArrayMaxValue.java


  1: //IntegerArrayMaxValue.java
  2: /*
  3: Finds the maximum value in an array of integers.
  4: Uses a recursive function which applies one recursive call
  5: to a portion of the array that becomes smaller and smaller.
  6: */

  8: public class IntegerArrayMaxValue
  9: {
 10:     public static void main(String[] args)
 11:     {
 12:         System.out.println("\nThis program illustrates the application "
 13:             + "of recursion to an array.\n");

 15:         int[] a1 = {5, -6, 12, 43, 17, -3, 29, 14, 35, 4};
 16:         System.out.println("Maximum value in the first array:  "
 17:             + maxArrayValue(a1, 0, 9));

 19:         int[] a2 = {-5};
 20:         System.out.println("Maximum value in the second array: "
 21:             + maxArrayValue(a2, 0, 0));

 23:         int[] a3 = {1, 3, 5, 7, 9, 11};
 24:         System.out.println("Maximum value in the third array:  "
 25:             + maxArrayValue(a3, 0, 5));

 27:         int[] a4 = {26, 24, 22, 20, 16, 12, 0};
 28:         System.out.println("Maximum value in the fourth array: "
 29:             + maxArrayValue(a4, 0, 6));
 30:     }

 32:     public static int maxArrayValue
 33:     (
 34:         int a[],
 35:         int first,
 36:         int last
 37:     )
 38:     /**
 39:     Compute the maximum value from the index interval
 40:     [first, last] in the array.
 41:     @return The maximum value from the interval [first, last].
 42:     @param a An array of integers.
 43:     @param first The lower index of the interval to be examined.
 44:     @param last The upper limit of the interval to be examined.
 45:     <p>Pre<p>The array a has been initialized, and
 46:     0 <= first <= last <= (number of elements in a) - 1.
 47:     <p>Post<p>No side effects.
 48:     */
 49:     {
 50:         if (first == last)
 51:             return a[first];
 52:         else
 53:         {
 54:             int maxOfRest = maxArrayValue(a, first+1, last);
 55:             return (a[first] > maxOfRest) ? a[first] : maxOfRest;
 56:         }
 57:     }
 58: }