简体   繁体   English

算法的大O分析

[英]Big O Analysis for Algorithm

Next in my series of Big O questions that I can't find the answer to 接下来在我的Big O问题系列中,我找不到答案

Take the following example 以下面的例子为例

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

Would this still be considered O(n^2)? 这仍然被认为是O(n ^ 2)? I only ask because I feel that this has to be less that O(n^2), since the inner loop is executing less and less for every iteration of i (since j is starting closer and closer to someNumber). 我只是问,因为我认为这必须小于O(n ^ 2),因为内部循环对于i的每次迭代执行越来越少(因为j越来越接近someNumber)。

Thanks 谢谢

The outer loop runs n times. 外循环运行n次。 The inner loop starts out running n times, but decreases with each iteration of the outer loop, until the last iteration where it only runs once. 内循环开始运行n次,但随着外循环的每次迭代而减少,直到它只运行一次的最后一次迭代。 The code inside the inner loop will run 内循环内的代码将运行

n + (n−1) + ... + 2 + 1 n +(n-1)+ ... + 2 + 1

times. 倍。

That can be simplified to n(n + 1)/2 ( proof ), or n 2 /2 + n/2, or finally (n 2 + n) / 2. Since the first term is n 2 , the algorithm is in O(n 2 ). 这可以简化为n(n + 1)/ 2( 证明 ),或n 2/2 + n / 2,或最后(n 2 + n)/ 2.由于第一项是n 2 ,算法在O(n 2 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM