简体   繁体   中英

Difference between time complexity O(ab) and O(N^2)

I assume that this code ideally representation of O(n^2) complexity. The reason is for function in another for function

for (int i = 0; i < array. length; i++) 
    for (int j = 0; j < array.length; j++) 
             System.out.println(array[i] + "," + arrayfj]); 

Also, I read that code below is represent O(ab) time complexity. But why is that way? I don't undersant, because if (arrayA[i] < arrayS[j]) , this is constant and we can ignore that.

for (int i = 0; i < arrayA.length; i++) 
   for (int j = 0; j < arrayB.length; j++) 
       if (arrayA[i] < arrayS[j]) 
           System.out.println(arrayA[i] + + arrayBfj]); 

This also mentioned as O(ab), although for (int k = 0; k < 160800; k++) is also as constant

for (int i = 0j i < arrayA.length; i++)
       for (int j = 0; j < arrayB.length; j++)
          for (int k = 0; k < 160800; k++) 
             System.out.println(arrayA[i] + "," + arrayB[j]);

Different sites write different information about it.

If the first case, each array is the same length (n), and n*n prints are done.

In the second, the sizes of the arrays are a & b, and a*b ifs are done, and (potentially) that many prints are done (maybe everything in A is less than everything in B).

In the third, the sizes of the arrays are a & b, and (a*b)*160800 prints are done, but the constant can be ignored.

I also think that the OP is missing an important point. It's not that the first algorithm is O(n) . It's that the first algorithm is O(n) where n is the length of the array. Though it is usually implicit, the variables we use in big-O notation must have some relationship to the inputs to the algorithm.

Likewise, the second algorithm is O(ab) , where a=length(arrayA) and b=length(arrayB) .

Regarding the if statement. If the if statement is false, then those two lines run in some small constant time. If the if statement is true, then those two lines run in some slightly larger, but still small constant time. The goal of big-Oh notation is to ignore constants, and just to see how the running time of the algorithm is related to the inputs. So a constant is a constant is a constant.

Likewise for the third program. The loop is run a constant number of times. Hence it takes a constant amount of time. A constant is a constant, even if it's large.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM