public class IntegerArrayMaxValue
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
13: (
14: "\nThis program illustrates the application "
15: + "of recursion to an array.\n"
16: );
18: int[] a1 = {5, -6, 12, 43, 17, -3, 29, 14, 35, 4};
19: System.out.println
20: (
21: "Maximum value in the first array: "
22: + maxArrayValue(a1, 0, 9)
23: );
25: int[] a2 = {-5};
26: System.out.println
27: (
28: "Maximum value in the second array: "
29: + maxArrayValue(a2, 0, 0)
30: );
32: int[] a3 = {1, 3, 5, 7, 9, 11};
33: System.out.println
34: (
35: "Maximum value in the third array: "
36: + maxArrayValue(a3, 0, 5)
37: );
39: int[] a4 = {26, 24, 22, 20, 16, 12, 0};
40: System.out.println
41: (
42: "Maximum value in the fourth array: "
43: + maxArrayValue(a4, 0, 6)
44: );
45: }
47: public static int maxArrayValue
48: (
49: int a[],
50: int first,
51: int last
52: )
53: /**
54: Compute the maximum value from the index interval
55: [first, last] in the array.
56: @return The maximum value from the interval [first, last].
57: @param a An array of integers.
58: @param first The lower index of the interval to be examined.
59: @param last The upper limit of the interval to be examined.
60: <p>Pre<p>The array a has been initialized, and
61: 0 <= first <= last <= (number of elements in a) - 1.
62: <p>Post<p>No side effects.
63: */
64: {
65: if (first == last)
66: return a[first];
67: else
68: {
69: int maxOfRest = maxArrayValue(a, first + 1, last);
70: return (a[first] > maxOfRest) ? a[first] : maxOfRest;
71: }
72: }
73: }