0

I have trouble finding the complexity of the following algorithm:

int count = 0;
for (int i = 0, i <n -1; i++) {
 for (int j = i +1; j < n; j++) {
 for (int k = n; k > n/2; k--) {
 count++;
 }
 }
}
int j = 0;
int num = count;
while(j < num) {
 for (int k = 0; k < 10; k++) {
 count++;
 }
 j++;
}

I got O(n) for the worst case. Is this right or did I mess up?

If someone could explain it would be great, maybe with what operations are happening per line. I'm getting really confused in the first part, since there are multiple nested for loops.

trincot
356k37 gold badges278 silver badges337 bronze badges
asked Mar 28, 2021 at 13:31
2
  • 1
    How did you get O(n^3)? As a math teacher would say, can you show you work? Commented Mar 28, 2021 at 13:32
  • 1
    Might be because of lack of proper understanding, but it was because of the three for loops in the first block, but I wasn't too sure especially with the "for (int k = n; k > n/2; k--)", since that would seem like log(n), right or am I wrong again? Commented Mar 28, 2021 at 13:39

1 Answer 1

1

It is indeed O(n3).

The outer two loops give all possible ways to select two distinct values (i, j) from a set with n values. This is a triangular number and thus O(n2).

The inner loop will make n/2 iterations, which is O(n/2) = O(n), so the first block of code represents O(n3).

The second part of the code has a while loop that makes count iterations, and we know that this count is O(n3). Its inner loop iterates a constant number of times, so that represents a constant time complexity: O(Cn3) = O(n3)

And so in total we have O(n3)+O(n3) = O(n3).

As there is no variable input besides n, nor any randomness, the number of iterations is completely determined by it, and so there is no notion of best or worst. There is just a fixed time complexity.

answered Mar 28, 2021 at 13:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.