Big O concept/Algorithm logic, not sure about my solutions, not too good with loops

时间:2015-07-28 16:47:39

标签: algorithm loops big-o time-complexity

So I just finished the following big O/time complexity questions below, but I'm not sure about my answers or the way I did them, if you are familiar with it, please check my answers and give me some advices to it. Since I always get confused when I do loops of Big O problems

1)

For each item N
    For each item N
      For each item N
        do some kind of processing
      EndFor
    EndFor

This one should be the easiest, O(n^3), but someone said it should be O(n)?

2)

For each item N
    x = N
    While (x > 1)
      For each item N
        do some kind of processing
      EndFor
      x = x / 2       Integer Division
    EndWhile
  EndFor

This one should be O ( n * log N), but I'm not sure because first part of loop is N, and second one is n/2.

3)

x = N
  While (x > 1)
    y = N
    While (y > 1)
      For each item N
        do some kind of processing
      EndFor
      y = y / 2     Integer Division
    EndWhile
    x = x / 2     Integer Division
  EndWhile

This one confuse me the most, it should be O(log n * log N), but if loops are nested together, don't I take the first N, and then times Log N?

4)

x = N
While (x > 1)
  do some kind of processing
   x = x / 2     Integer Division
EndWhile
y = N
While (y > 1)
  do some kind of processing    y = y / 2     Integer Division
EndWhile
For each item N
  do some kind of processing
EndFor

This one should be O(N * log N) also?

2 个答案:

答案 0 :(得分:2)

"For each item N" := O(N)

"While (x > 1) ... x = x / 2" := O(logN)

So:

(1) O(N^3)

(2) Looks like O(N) * O(logN) * O(N) = O(N^2 * log N) to me

(3) Looks like O(logN) * O(logN) * O(N)

(4) These loops aren't nested, so largest dominates: max( O(logN), O(logN), O(N) ) = O(N)

答案 1 :(得分:0)

1) Yes, the runtime is O(n^3).

2) This is O(n^2*log(n)). Solve this from the inside to the outside: The innermost loop is O(n) this O(n) work is performed log(n) times, so we get O(n*log(n)). The outermost loop performs this work O(n) times, so altogether O(n^2*log(n))

Now look at 3) again, this contains a similar mistake, you ignored the innermost loop.