2

In selection sort the outer loop time complexity will be O(n) and the inner loop time complexity will be (n(n-1))/2 then why have we added outer loop time complexity with inner loop : n + (n(n-1))/2 instead of multiplying?

As it is a nested loop then it must be multiplied. But if we multiply the time complexity, it will become O(n^3) instead of O(n^2)

3
  • Where are these expressions coming from? Commented Sep 24, 2024 at 17:45
  • 1
    In selection sort the inner loop is O(n), making the overall O(n^2). See here. Commented Sep 24, 2024 at 17:48
  • "As it is a nested loop then it must be multiplied" - This is false and invalidates your reasoning. Commented Sep 24, 2024 at 20:46

2 Answers 2

2

You asked:

why have we added outer loop time complexity with inner loop : n + (n(n-1))/2 instead of multiplying?

It is correct that in total the inner loop makes 𝑛(𝑛−1)/2 iterations, but those iterations are not the only work that is done. On top of that there is code outside that loop that executes 𝑛−1 times, and then a final comparison of the outer for that doesn't result in an iteration.

So yes, you would consider the complexity to be:

  O(𝑛 + 𝑛(𝑛−1)/2)

But this additional 𝑛 really is irrelevant in terms of big O. The above big O expression is equivalent to:

  O(𝑛 + 𝑛(𝑛−1)) = O(𝑛 + 𝑛²) = O(𝑛²)

Check out the rules on how you can simplify big O expressions on Wikipedia

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

Comments

1

In selection sort, the inner loop runs n - 1 times in the first iteration, n - 2 times in the second iteration, and so on until it runs 1 time in the last iteration.

The outer loop controls how many times the inner loop iterates.

The sum of the first n - 1 natural numbers is n * (n - 1) / 2, which has a complexity of O(n^2).

I encourage you to read the Selection sort article on Wikipedia.

Comments

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.