In: Computer Science
The following pseudocode finds the maximum element in an array of size n.
Int MAX (int A [ ], int n) { M = A[0]; for i = 1 to n – 1 if (A[i] > M) M = A[i] //Update the max return M; } |
Recursive version of this program:
Approach:
if(n == 1)
return arr[0];
return max(arr[n-1], recursive_function(arr, n-1));
Pseudocode:
Int MAX (int A [ ], int n) {
if (n == 1)
return A[0]
if(A[n-1] > MAX(A, n-1))
return A[n-1]
else
return MAX(A, n-1)
}
Now, let f(n) be the number of key comparisons performed by this algorithm, then from the above recursive algorithm, f(n) = f(n - 1) + 1
Here, 1 denotes 1 key comparisons happening in base case.
Now, solving f(n), given f(n) = 1 (base case)
f(n) = f(n-1) + 1
f(n-1) = f(n-2) + 1
...
...
f(2) = f(1) + 1
Here, adding RHS and LHS, f(n) = f(1) + n - 2 = n - 1
Therefore f(n) = n - 1
Now, proving this using Induction:
Base Case: f(n) = 1
Assume for n = k, this function is satisfied: f(k) = k - 1
Now, Proving it for n = k + 1
f(k + 1) = k + 1 - 1 = k
So, true for n = k + 1
Hence, the expression is true, PROVED