What is the complexity of this function with nested loops?

别说谁变了你拦得住时间么 提交于 2021-02-05 09:36:25

问题


What is the complexity of this code?

public class test5{
public static void main(String[] args) {
   int n = Integer.parseInt(args[0]);
   for (int i = 1; i<=n; i++) {
      for (int j = 1; j<=i; j++) {
         System.out.print ("*");
      }
   System.out.println();
   }

  for (int i = n; i>=1; i--) {
      for (int j = 1; j<=i; j++) {
         System.out.print ("*");
      }
   System.out.println();
   }
} 

}

My assumption is that it will take O(n^2) operations because n*(n/2) + n*(n/2). Am I right?


回答1:


You are correct, a tight upper asymptotic bound for both the first and second nested loop blocks—say T_A(n) and T_B(n), respectively—is O(n^2), and hence the function as a whole runs as O(n^2), asymptotically.

You can analyze this in detail using Sigma notation to count the number of basic operations in the inner loop blocks for each of the nested loop blocks T_A(n) and T_B(n):

Where we've treated the System.out.print ("*"); operation as basic operation.



来源:https://stackoverflow.com/questions/36913439/what-is-the-complexity-of-this-function-with-nested-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!