这个伪代码的运行时是什么?

时间:2017-02-10 18:43:01

标签: runtime pseudocode discrete-mathematics

i = 1;  
while (i <= n)
   j = i;  
   x = x+A[i];  
   while (j > 0)  
     y = x/(2*j);  
     j = j/2; // Assume here that this returns the floor of the quotient  
   i = 2*i;
return y;

我不确定我的答案,我得到O(n 2 )。

1 个答案:

答案 0 :(得分:1)

允许删除xy变量,因为它不会影响复杂性。

i = 1;  
while (i <= n)
   j = i;    
   while (j > 0)  
      j = j/2;  
   i = 2*i;
  1. 在内循环中,每次将j除以2,实际上它不是O(logn)的衬里。例如,当j为16时,您将执行5 ( O(log16)+1 )步骤:8,4,2,1,0。
  2. 在外部循环中,您每次将i乘以2,因此它也是O(logn)
  3. 因此总体复杂度为O(logn * logn)

相关问题