1

I have a simple algorithm that prints the two dimensional matrix (m*n, m and n are different numbers):

for(i=0;i<m;i++)
    for(j=0;j<n;j++)
        Console.WriteLine("{0}",A[i,j]);

I read that the big O notation for this algorithm is O(n^2); Could somebody explain me what is the "n^2" in that statement? If this is number of elementary operations, then it should be m*n, not n^2?

Rapptz
  • 20,807
  • 5
  • 72
  • 86
user3660090
  • 87
  • 13

4 Answers4

4

In reality it should me m*n. We can assume it to be the number of elementary operations in this case, but the actual definition is its "the upper bound of the number of elementary operations."

Bharath
  • 66
  • 4
0

Yeah, time complexity of for the specified block of code is O(n * m). In simple words, that means your algo does <= k * n * m operations, k is some small constant factor.

juver
  • 236
  • 2
  • 8
0

With for-loops, the complexity is measured as O(N) * the block inside the for-loop. The first for-loop contains a second for-loop so the complexity would be 0(N) * 0(N) = O(N^2). The inner for-loop contains a simple output statement, which has a complexity of 0(1) The N corresponds to the number of inputs so the time taken to execute the code is proportional to the number of items squared.

user1849060
  • 621
  • 3
  • 10
  • 20
0

first for loop runs for m-1 times and second for loop runs for n-1 times..

m-1 times = 1+2+3....m-1 times (same for second forloop)

we know that sum of natural numbers is x(x-1)/2 = x^2/2 - x/2

there are 2 loops so adding them gives you 2(x^2/2-x/2)

in Bing O notation we consider only the most dominant value and ignore coefficients, so we get x^2

so O(N) = x^2

Rakesh
  • 353
  • 1
  • 4
  • 21