Static void doIt (int n ) {
int i; // 1 operations
int j; ← (2 x n) // 1 operations
while loop (j > 0) { // n operations
I; ← n // (n+1) operations
while loop ( i>= 1) { // (n*n) operations
I; ← i/2 // sqrt (n) operations
}
j; ← j -1 // (n+1) operations
}
}
Static int myMethod (int n) {
sum; ← // 1 operations
for i ← 1 to n { // (n operations)
sum = sum + doIt(i); // (n+1) operations
}
return 1; // a
}
Here is my solution for this pseudocode, but not sure if its correct
T(n) = 1 + 1 + n + (n+1) + (n*n) + sqrt(n) + 1 + n + (n+1) + a = n^2 + 5n + 5 + sqrt(n)
big-o complexity = O(n^2)
I'll make a few assumptions. For instance, I'll assume tht
int j; ← (2 x n)initializesjwith2*n. I wouldn't expect this semicolon there, but I can't continue otherwise.With that in mind, your solution is incorrect.
Since
jis initialized with2nand decreases by one unit at a time, then this will perform2n + 1steps, notn. The decrement will perform2nsteps and the verification brings the+1into the equation.Then there's the inner loop:
Assuming
iandIare the same variable, then the assignmentI <- I/2will perform notsqrt(n), but up tolog2(n)steps in each iteration of the outer loop. Therefore thewhileloop will run the product of the external loop by that value, that is, something upper-bounded by2n × log2(n).If you fix and sum everything, you'll see that
doItis O(n logn). The exact value involves the ceiling oflog2(n)and a few constants.The other function,
myMethod, has a for loop:This line will be run
ntimes, notn + 1. If you don't need the exact function, that is, if you are only looking for the upper-bound in O notation, then this is O(n).Since you are calling an O(n logn) algorithm O(n) times, this makes your entire algorithm O(n² logn).