user10826235
user10826235

Reputation: 69

Comparison of time complexity

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!

Upvotes: 3

Views: 169

Answers (1)

Leandro Caniglia
Leandro Caniglia

Reputation: 14858

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))

Upvotes: 2

Related Questions