-2
$\begingroup$

This question already has an answer here:

Hey I am studying for my intro algorithms class final and I'm not sure if I'm understanding this question correctly (its from a sample final exam). If someone could explain this to me that would be awesome.

The following code processes A which is an n-by-n matrix of ints. The method nextInt() is O(1), and the method findMax() is O(n). What is the complexity of the given code as a function of the problem size n? Show the details of your analysis.

for(int i = 0; i < n; i++){

    for(int j = 0; j < n; j++)
        A[i][j] = random.nextInt(); 

    System.out.println(findMax(A[i]));
}

Without the methods the for loop complexity is O(n^2). Now the random.nextInt() complexity is O(1) but it is run n^n time does this effect the complexity of this. Sorry I'm a little sleep deprive. If someone can help me answer this question that would be awesome

$\endgroup$

marked as duplicate by David Richerby, D.W., Raphael Dec 18 '14 at 23:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2
$\begingroup$

Here are a few hints:

1) Nothing is run n^n times (statement in the inner loop will be run O(n^2) times).

2) To figure out the complexity of an algorithm using order-of-growth (big 'Oh') notation, you just need to figure out the complexity of the highest-complexity procedure. For example, the complexity of the following is O(n^2), even though the first statement has complexity O(n).

System.out.println(findMax(A[i]));  <-- O(n)

for (int i = 0; i < N; i++) { <- O(N)
    for (int j = 0; j < N; j++) { <- O(N)
        System.out.println("Something useless"); <- O(1)
    }
}

3) Why is the "loop complexity" O(n^2)? Because you're running running an O(n) process within an O(n) process. What does the same logic tell you about the complexity of the inner loop operation (A[i][j] = random.nextInt();); how many times is the O(1) process nextInt run?

$\endgroup$
  • $\begingroup$ I may be wrong still don't full understand this completely. 2) O(1) is run N^2 times correct. Then the findMax(a[i]) is n and is run N times which means N^2 times, then the nested for loop complexity is O(n^2). Would this mean the complexity is O(N^4) or O(n^2)? Sorry about this might be a dumb question. Thanks for you reply :) $\endgroup$ – arberb Dec 20 '14 at 2:07
  • 1
    $\begingroup$ If you run a O(n^2) and then another O(n^2) process, what's the overall order of growth? Might be easier to think about in terms of O(1) processes. If I execute a constant number of O(1) processes (like 5 print statements), what's the overall order of growth? $\endgroup$ – James Evans Dec 20 '14 at 2:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.