a. Suppose that Event(i) is a boolean function that returns true for about n0.2 values of i < n.
for(int i=0;i<n;i++)
{
if(Event(i))
{
for(int j=0;j<i*i;j++)
{
g(n);
}
}
}
What is the order of execution (i) if g(n) is order n? (ii) if g(n) is order log(n)? (iii) if g(n) is order nlog(n)?
b. Solve the recurrence T(n)=7T(n/2)+n2
(As usual, we want only an order for the solution.)
c. Find the recurrence relationship for the following function.
(You can be fairly "approximate" about it.)
int f(int k, int m)
{
if(k<m)
{
int sum=1;
mid1=k+(m-k+1)/3;
mid2=k+2*(m-k+1)/3;
sum=sum+f(m,mid1)+f(mid2,n);
return(sum);
}
}
d. Solve the recurrence for f letting Tf(n) be the time required for f to run when n=(m-k+1), i.e., the range of values in f.
e. Find f(0,1), f(0,2), f(2,8), and f(0,12).
f. Here is a simple procedure that is designed to find the second largest integer in integer array A. Prove that it is correct using preconditions, postconditions, and loop invariants in your proof. Note that A.length is the number of items in A.
int FindSecond(int [] A)
{
int largest, secondlargest;
if(A[0]>A[1])
{
largest=A[0];
secondlargest=A[1];
}
else
{
largest=A[1];
secondlargest=A[0];
}
for(int i=2;i<A.length;i++)
{
if(A[i]>largest)
{
secondlargest=largest;
largest=A[i];
}
else if(A[i]>secondlargest)
{
secondlargest=A[i];
}
}
return(secondlargest);
}
g. Prove that the following function finds xn where x is a real number and n is a nonnegative integer. Your proof should be by induction. The function square(y) returns y*y.
double power(double x,
int n)
{
if(n==0) return(1.0);
else if(n==1) return(x);
else if((n%2)==0) return(square(power(x,n/2)));
else return(square(power(x,n/2))*x);
}
h. Do a complete analysis of the function in g.