Search code examples
big-opseudocodeoperations

Big O number of operations


How do you compute the number of operations each line of code would take.

Example.

Algorithm find2D (A,x)
    arrLength = A.length
    for j <- 1 to arrLength – 1 do
         for k <- 1 to arrLength – 1 do
                if A[j][k] = x then
                  return true
          increment k
    increment j
return false

I came up with this pseudo code. So I'm not really sure how to count the number of operations each line of code takes.

So like the first loop would be 1+n operations since you have to set the j, compare j to arrLength - 1, and it will loop n-1 times. So that gives you n-1 + 1 + 1 which is n+1 operations.

So for the second loop would it just be the same thing even though its nested.

I'm a little confused on the A[j][k] = x comparison, how many operations would that be.

Thanks.


Solution

  • Big-Oh is asymptotic, so you shouldn't be concerned with the "1" in "1+n".

    If all you're looking for is the Big-Oh classification of that code, simply consider that you have two loops, one nested inside the other, and each loop does some constant number of operations per element. Then the inside loop is O(n), and the outside loop is executing the inside loop n times, so the outside loop is O(n^2). Then the whole function is O(c+n^2) where c is the constant number of operations from the code surrounding the outside loop. Since Big-Oh is asymptotic, the c disappears and your function is O(n^2).

    If you're trying to calculate the exact number of operations the code takes, you'll probably need to establish what abstract machine you're using.

    Hope this helps.