What is Big O of a loop?

前端 未结 6 832
离开以前
离开以前 2020-12-03 15:02

I was reading about Big O notation. It stated,

The big O of a loop is the number of iterations of the loop into number of statement

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 15:36

    O(n) is used to messure the loop agains a mathematical funciton (like n^2, n^m,..).

    So if you have a loop like this

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

    The best describing math function the loops takes is calculated with O(n) (where n is a number between 0..infinity)

    If you have a loop like this

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

    Means it will took O(n*2); math function = n*2

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

    This loops takes O(n^2) time; math funciton = n^n This way you can calculate how long your loop need for n 10 or 100 or 1000

    This way you can build graphs for loops and such.

提交回复
热议问题