Question
1. Consider the following iterative function for problems 3 and 4: int triangular(int n) { int result = 0; for (int i = 1; i
1. Consider the following iterative function for problems 3 and 4:
int triangular(int n)
{
int result = 0;
for (int i = 1; i <= n; i ++)
result += i;
return result;
}
Rewrite the function triangular using recursion and add preconditions and postconditions as comments.
Prove by induction that the recursive function you wrote in the previous problem is correct.
2.Suppose the number of steps required in the worst case for two algorithms are as follows:
Algorithm 1: f(n) = 10n2 + 6
Algorithm 2: g(n) = 21n + 7
Determine at what point algorithm 2 becomes more efficient than algorithm 1.
3.
Given the following function that evaluates a polynomial whose coefficients are stored in an array:
double evaluate(double[] coefficients, int n, double x)
double result = coefficients[0];
double power = 1;
for (int i = 1; i < n; i++)
power = power * x;
result = result + coefficients[i] * power;
return result;
Let n be the length of the array. Determine the number of additions and multiplications that are performed in the worst case as a function of n.
4.
Given the following recursive binary search algorithm for finding an element in a sorted array of integers:
int recursiveBinarySearch(int[] array, int target, int left, int right)
{
if (left > right)
return -1;
int middle = (left + right) / 2;
if (array[middle] == target)
return middle;
if (array[middle] > target)
return recursiveBinarySearch(array, target, left, middle - 1);
return recursiveBinarySearch(array, target, middle + 1, right);
}
Assume n is the length of the array. Find the initial condition and recurrence equation that expresses the execution time for the worst case of this algorithm and then solve that recurrence.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started