0

I have calculated the time complexity of the following C function and it is coming to theta (nlogn).Can you tell me whether i am wrong,the answer given was theta(n^2logn)?I have just started reading about these concepts.

int unk(int n)
{
  int i,j,k=0;
  for(i=n/2;i<=n;i++)
     for(j=2;j<=n;j=j*2)
        k=k+(n/2);
  return k;
}

What I have done is:The outer loop executes for (n/2+2) times,inner loop executes for (n/2+1)(logn+1) times and the statement in the body of the loop executes (n/2+1)(logn) times.So the total running time comes to theta(nlogn).(Assume all the costs to be 1 and the log to be a binary logarithm).

C_beginner
  • 305
  • 1
  • 4
  • 12

1 Answers1

4

I think your answer is right, it is theta(nlogn) indeed. However, your analysis seems somewhat wrong.

The outer loop executes O(n/2) times.

The inner loop executes O(logn) times per iteration of the outer loop.

By multiplying the two and dropping the constants, you arrive at O(n) * O(logn) = O(nlogn).

Harshal Pandya
  • 1,622
  • 1
  • 15
  • 17
  • Yes,the outer loop executes for (n/2)+1+1 times(the last 1 is for execution before termination of the loop).So each of (lgn+1) times of the inner loop get executed for (n/2+1) times of the outer loop.Therefore the statement inside the loop gets executed for (n/2+1)lgn times. – C_beginner Jul 29 '13 at 01:42
  • Summing up (n/2+2)+(n/2+1)(lgn+1)+(n/2+1)lgn gives theta(nlgn) – C_beginner Jul 29 '13 at 01:53
  • Well what can I say, thats not how you calculate the complexity. You don't add things up that way. – Harshal Pandya Jul 29 '13 at 01:55