How would you go about finding the complexity of this algorithm?

前端 未结 2 1436
既然无缘
既然无缘 2021-01-24 04:32
function alg1(n)
1 a=0
2 for o=1 to n do
3     for t=1 to o do
4         for k=t to o+t do
5         a=a+1
6 return(a)

If anyone could guide me to how

2条回答
  •  面向向阳花
    2021-01-24 05:00

    We can compute the exact number of increments this code executes. First, let's replace

    for k=t to o+t do
    

    with

    for k=1 to o+1 do 
    

    After this change, two inner loops looks like this

    for t=1 to o do
        for k=1 to o+1 do
    

    The number of iterations of these loops is obviously o*(o+1). The overall number of iterations can be calculated in the following way:

    We can exclude coefficients and lower order terms of the polynomial when using big-O notation. Therefore, the complexity is O(n^3).

提交回复
热议问题