问题
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