complexity of code

前端 未结 6 1203
借酒劲吻你
借酒劲吻你 2021-01-14 07:33

what is the complexity of a program having only one loop, is it log n? can someone give me some ideas about estimating complexity of codes?

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 08:17

    To get the Big-O complexity of a piece of code, you need to ask yourself "how many iterations are done"?

    The problem is of course, that it isn't always easy to figure it out from the code itself, sometimes it's just better to look at the big picture and calculate the amount of operations done.

    Examples:

    For (i = 0 ; i < n ; i++ ) {
       //Do stuff
    }
    

    This is a on complexity

    For (i = n ; i > 0 ; i= i/2 ) {
       //Do stuff
    }
    

    This is a logn complexity... Because in each iteration i is cut in half.

    void Mess (int n) {
        for (i = 0 ; i < n ; i++) {
             //Do stuff
             Mess(n-1);
        } 
    }
    

    Now this looks like a simple loop, nut because it calls itself with recursion, it's actually quite a mess.... Each iteration calls itself n times with n-1.
    So here it would be easier to think from the end. If n == 1 , there's 1 iteration. If n == 2 then it calls the previous scenario twice.
    So if we'll call the function enter image description here, we can see what we'll get this recursively: In Which in the end will of course give us n!

    Bottom line, it's not always trivial.

提交回复
热议问题