1

I'm having a hard time understanding algorithm analysis, especially the following example:

for (int i = 1; i < n^3; i = 2*i){
  for (int j = 6*n; j > 0; j = j-2){
  }
}

So my understanding of this is that the outer loop is O(nlogn) as i is multiplied by a constant amount, I'm unsure if the n^3 makes any difference or not.

The inner loop confuses me the most though. I think it's O(n) as j is decremented by a constant amount but I'm uncertain whether the 6*n and the j > 0 have any influence.

If i'm correct then this entire algorithm would be O(nlogn)? Uncertain how to express the time complexity T(n) of this though.

Any insights would be hugely appreciated.

1
  • 1
    Note that ^ is the XOR operator in most programming languages. Commented Aug 1, 2015 at 4:43

1 Answer 1

3

The outer loop is not O(nlogn) - since i is multiplied in 2 every loop, it goes: 2, 4, 8, 16, 32... this means that it will take a log(n^3) steps for i to reach n^3 (the base of the log is 2).

More formal: O(log(n^3)) = O(3logn) = O(logn)

In the inner loop j is initialized to 6*n and goes down in steps of 2. This means that it'll take 6n/2 steps for j to reach zero.

More formal: O(6n/2) = O(3n) = O(n)

So the complexity of the code section is O(n) * O(logn) = O(nlogn)

Sign up to request clarification or add additional context in comments.

7 Comments

Sorry, do you mind elaborating? Still a bit confused
@Dan_JAVA_SQL can you be more specific: which step in the process is unclear ?
The outer loop makes sense now, what would have to be different for the outer loop to be O(nlogn)? Why are you dividing 6n by 2? Thanks
The only thing that is not covered is your question in the comment above: "what would have to be different for the outer loop to be O(nlogn)?". This question is a bit vague. I guess that if you'll run the outer loop inside another loop that takes n steps...
Great this is all starting to make sense! the only thing I still don't quite get is "since i is multiplied in 2 every loop, it goes: 2, 4, 8, 16, 32... this means that it will take a log(n^3) steps for i to reach n^3" wont it take log(n^2) as it goes 2, 4 ,8...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.