Big O: How to determine runtime for a for loop incrementation based on outer for loop?

后端 未结 2 1184
执笔经年
执笔经年 2021-01-27 08:45

I have the following algorithm and the runtime complexity is O(N^2) but I want to have a deeper understanding of it rather than just memorizing common runtimes.

What wo

2条回答
  •  孤街浪徒
    2021-01-27 09:14

    What would be the right approach to break it down and analyze it

    Take pencil and paper and put down some loops unwraped:

         i        inner loops per i
    -------------------------------
         1               length - 1  
         2               length - 2
        ..                       ..  
         k               length - k 
        ..                       ..
    length - 1                    1
    length                        0
    

    Now, in order to obtain the total time required, let's sum up the inner loops:

     (length - 1) + (length - 2) + ... + (length - k) ... + 1 + 0
    

    It's an arithmetic progression, and its sum is

     ((length - 1) + 0) / 2 * length == length**2 / 2 - length / 2 = O(length**2)
    

提交回复
热议问题