3

I got those two algorithms with two for loops each - the first algorithm has in my opinion a quadratic running time. Does the second algorithm have the same running time - O(n^2)?

Algorithm 1:

for (int i = 1..n) { 
     for (int j = 1..n) {
          // sort m[i, j]
     } 
}

Algorithm 2:

for (int i = 1..n) { 
     for (int j = i..n) {
          // sort m[i, j]
     } 
}

I checked previous similar posts (Big O notation) but couldn't find anything to solve my problem - if you do so, please point me in the right direction.

Thanks!

1 Answer 1

2

Let's analyze Algorithm 2, the other one is similar.

Let's first agree in that sort m[i, j] is O((j-i)lg(j-i)).

Alg 2  = O(sum_{i=1}^n sum_{j=i}^n (j-i)lg(j-i))
      <= O(sum_{i=1}^n sum_{j=i}^n (n-i)lg(n-i))
      <= O(sum_{i=1}^n (n-i)^2 lg(n-i))
       = O(sum_{i=1}^n i^2 lg(i))
      <= O(sum_{i=1}^n i^2 lg(n))
       = O(n^3 lg(n))

On the other hand

Alg 2  = O(sum_{i=1}^n sum_{j=i}^n (j-i)lg(j-i))                      ; take 1/2 of terms
      >= O(sum_{i=n/2}^n sum_{j=(i+n)/2}^n (j-i) lg(j-i))
      >= O(sum_{i=n/2}^n sum_{j=(i+n)/2}^n (n-i)/2 lg((n-i)/2)))      ; because j>=(i+n)/2
      >= O(sum_{i=n/2}^n ((n-i)/2)^2 lg((n-i)/2)))
      >= O(sum_{i=n/2}^{(n+n/2)/2} ((n-i)/2)^2 lg((n-i)/2)))          ; 1/2 of terms
      >= O(sum_{i=n/2}^{3n/4} (n/8)^2 lg(n/8))                        ; -i >= -3n/4
       = O(n^3 lg(n))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanksfor your answer. So in your opinion it would be both times O(n³)?

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.