繁体   English   中英

此for循环的运行时复杂度是多少?

[英]What is the run time complexity of this for loop?

我试图找出此算法的运行时复杂性。

public static void main(String[] args) throws InterruptedException{

  for (int N=100; N<=1000000; N=N*5) {  
   long start = System.currentTimeMillis();
   for (int i = 1; i <= N; i++) {     
      for (int j = 1; j <= Math.pow(N,1.5); j++) {
      i = i*2;
      j = j*2;
      Thread.sleep(10); 
     } 
    }
   long stop = System.currentTimeMillis();
   long elapsed = (long)(stop - start);
   System.out.println();
   System.out.println("For N=" + N + " RT in msec: "+elapsed); 
 }
}

第一个for循环:

for (int N=100; N<=1000000; N=N*5) // runs n/5 times, so O(n). 

第一个内部循环:

for (int i = 1; i <= N; i++) // runs n times. 

第二个内部循环:

for (int j = 1; j <= Math.pow(N,1.5); j++) { // we can consider Math.pow O(1)
      i = i*2;
      j = j*2;
      Thread.sleep(10); 
     } 

因此,通过将所有O(n)* O(n)* O(1)= O(n ^ 2)相乘,我的答案正确吗? 我对此有些困惑。 将不胜感激对此任何澄清。 谢谢

第一个循环实际上是O(k) ,其中5^k = N 因此, k = log_5(N) 第一个内部循环为true(在O(n) )。 第二个内部循环j每次是2 因此,是O(h) 2^h = N^1.5 因此, h = 1.5 log(N)

总之,该算法为O(log_5(N) * N * log(N)) = O(N log^2(N))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM