1: // Filename: MAXINTA2.CPP
2: // Purpose: Finds the maximum value in an array of integers.
3: // Uses a recursive function which breaks the array into
4: // two parts and applies a recursive call to each part.
6: #include <iostream>
8: int MaxArrayValue(const int [], int, int);
10: int main()
11: {
12: int a1[10] = {5, -6, 12, 43, 17, -3, 29, 14, 35, 4};
13: int a2[10] = {-5, -6};
14: int a3[] = {1, 3, 5, 7, 9, 11};
15: int a4[] = {26, 24, 22, 20, 16, 12, 0};
17: cout << endl;
18: cout << "The maximum value in the first array is "
19: << MaxArrayValue(a1, 0, 9) << "." << endl;
20: cout << endl;
21: cout << "The maximum value in the second array is "
22: << MaxArrayValue(a2, 0, 9) << "." << endl;
23: cout << endl;
24: cout << "The maximum value in the third array is "
25: << MaxArrayValue(a3, 0, 5) << "." << endl;
26: cout << endl;
27: cout << "The maximum value in the fourth array is "
28: << MaxArrayValue(a4, 0, 6) << "." << endl;
29: cout << endl;
31: return 0;
32: }
35: int MaxArrayValue(/* in */ const int a[],
36: /* in */ int first,
37: /* in */ int last)
38: // Pre: The array "a" has been initialized, and
39: // 0 <= first <= last <= number of elements in "a" - 1.
40: // Post: Function value is the maximum value in the array "a"
41: // between the indices "first" and "last".
42: {
43: int lowerMax, upperMax;
45: if (first == last)
46: return a[first];
47: else
48: {
49: lowerMax = MaxArrayValue(a, first, (first+last)/2);
50: upperMax = MaxArrayValue(a, (first+last)/2 + 1, last);
51: return (lowerMax > upperMax) ? lowerMax : upperMax;
52: }
53: }