算法的运行时间(大O))

Rav*_*sla 5 algorithm time-complexity asymptotic-complexity

我正在计算这个算法的运行时间?

                              Cost      No Of Times

for(j=1;j<=n-1;j++){          c1       n(loop will run for n-1 times +1 for failed cond              

    for(i=0;i<=n-2;i++){      c2       n*(n-1) (n-1 from outer loop and n for inner 

        if(a[i]>a[i+1]){      c3       (n-1)*(n-1)

            Swap              c4       (n-1)*(n-1) {in worst case }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在最坏的情况下, T(n)= c1*n + c2*(n-1)n + c3(n-1)(n-1)+ c4*(n-1)(n-1) 即O(n ^ 2)

在最好的情况下:

T(n)= c1*n + c2*(n-1)n + c3(n-1)(n-1) ,其为O(n ^ 2).

但实际上在最佳情况下,冒泡排序具有时间复杂度O(n). 谁能解释一下?