a. Suppose that Event(i) is a boolean function that returns true for
about n0.2 values of i < n. In other words, the
probability of the if being true is roughly n0.2/n=1/n0.8.
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;
int mid1=k+(m-k+1)/3;
int mid2=k+2*(m-k+1)/3;
sum=sum+f(k,mid1)+f(mid2,m);
return(sum);
}
else
return(1);
}
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. Analyze the algorithm.
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. Do a thorough analysis to find T(n) for the following function.
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. Analyze the following code segment:
for(int
i=0;i<n;i++) {
for(int j=0;j<i;j++) {
for(int k=0;k*k<n;k++) {
if(k>5) then f(n);
else g(n);
}
}
}
}
when: a. f(n) takes time n and g(n) takes time
n*n*n b. f(n) takes constant time and g(n) takes time
n*n