开发者

What's the efficiency of this program?

What's the efficiency (in Big O notation) of a simple program that traverses a 2D array of ints and outputs each element.

Take the following code as an example:

public static 开发者_JAVA百科void main(String args[])
{
   int[] array = {{1,2,3,4},
                  {5,6,7,8},
                  {9,10,11,12},
                  {13,14,15,16}};

    for(int i = 0; i < array.length; i++)
    {
       for(int j = 0; j < array[i].length; j++)
       {
          System.out.println(array[i][j]);
       }
    }
}


O (n*m) where n the number of arrays (first dimenstion) and m the max size of each internal array (second dimension)


I'd even note that the size of m is comparable to the size of n and make this O(n2).


Considering that your algorithm visits every element in the array once, it is O(n) where n is the size of the 2D array.


Since you traverse each element in the matrix once, it is O(nm), where n is the number of rows, and m is the number of columns.


It will take O(n) because this algorithm will take the same time if you put the same number of elements into a one-dimensional array and iterate through it in a single loop.


This is O(n^2) since the inner loop is dependent on the outside loop. O(n*m) rarely describes runtime of loops - that is used for graphs. Eg: O(V+E) vertices and edges.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜