Finding the largest value in an array is a problem that can be solved naturally using a scan algorithm. The idea is to keep track of the largest value seen so far. Suppose array A is currently as follows.
A[0] | = | 20 |
A[1] | = | 6 |
A[2] | = | 35 |
A[3] | = | 53 |
A[0] | = | 28 |
Here is a plan for a loop to find the largest value. Notice that variable L, which hold the largest value seen so far, is initially set to A[0], since there is no sensible value to choose for the largest value in an empty array.
i | L | |
---|---|---|
0 | 20 | |
1 | 20 | |
2 | 35 | |
3 | 53 | |
4 | 53 |
That loop plan has an invariant: L = max(A[0], … A[i]). Check that the invariant assertion is true at each line.
Here is the algorithm written in C++.
int largest(int* A, int n) { int L = A[0]; int i = 0; while(i < n) { i++; L = max(L, A[i]); } return L; }
A recursive version of largest relies on two facts.
largest(A, 1) = A[0]. That is, if array A has only one member, then the largest value must be the first value, A[0].
largest(A, n) = max(A[n−1], largest(A, n−1)). That is, find the largest value v of the first n−1 values in array A. Then the largest of the first n values in array A is clearly either A[n−1] or v.
Check that equation for the array A shown above for values of i from 0 to 4.
Here is a C++ function that follows those two equations.
int largest(int* A, int n) { if(n == 1) { return A[0]; } else { return max(A[n-1], largest(A, n-1)); } }
What if the loop version of largest initializes L = 0 rather than L = A[0]? Does the function definition still work? Why or why not? Answer