算法的算法分析(big-O)

标签 algorithm big-o notation asymptotic-complexity

我正试图帮助一位 friend 分析他的算法的复杂性,但我对大 O 表示法的理解非常有限。

代码是这样的:

int SAMPLES = 2000;
int K_SAMPLES = 5000;

int i = 0; // initial index position    
while (i < SAMPLES)
{
    enumerate();                       // Complexity: O(SAMPLES)
    int neighbors = find_neighbors(i); // Complexity: O(1) 

    // Worst case scenario, neighbors is the same number of SAMPLES
    int f = 0;
    while (f < neighbors) // This loop is probably O(SAMPLES) as well.
    {
        int k = 0; // counter variable
        while (k < K_SAMPLES) // Not sure how to express the complexity of this loop.
        {                     // Worst case scenario K_SAMPLES might be bigger than SAMPLES. 

            // do something!

            k++;
        }
        f++;
    }

    i++;
}

代码中有 2 个函数,但我能够识别它们的复杂性,因为它们很简单。然而,我无法表达内部 while 循环的复杂性,但即使在测量之后,我仍然需要帮助将所有这些复杂性组装成一个表示算法计算复杂性的公式。

在这件事上我非常需要帮助。谢谢!

最佳答案

从最内层循环到最外层循环的最坏情况分析 (with mild abuse of the "=" sign):

->  O(K_SAMPLES)                    -- complexity of just the k-loop

->  neighbors * O(K_SAMPLES)         -- complexity of f-loop accounted for
 =  SAMPLES * O(K_SAMPLES)          -- since neighbors = SAMPLES in worst case
 =  O(SAMPLES * K_SAMPLES)

->  O(SAMPLES) + O(SAMPLES * K_SAMPLES)  -- adding complexity of enumerate()
 =  O(SAMPLES + SAMPLES * K_SAMPLES)
 =  O(SAMPLES * K_SAMPLES)

SAMPLES 项被删除,因为 SAMPLES * K_SAMPLES 渐近增长得更快。更正式地说,

When C >= 2, SAMPLES >= 1, K_SAMPLES >= 1 then

SAMPLES + SAMPLES * K_SAMPLES  <=  C(SAMPLES * K_SAMPLES)
SAMPLES * (K_SAMPLES + 1)  <=  SAMPLES * C * K_SAMPLES
K_SAMPLES + 1  <=  C * K_SAMPLES

有关具有多个变量的大 O 的更多信息,请参阅 here .继续我们的最后一个循环:

->  SAMPLES * O(SAMPLES * K_SAMPLES)    -- complexity of i-loop accounted for
 =  O(SAMPLES^2 * K_SAMPLES)

请注意,根据 find_neighbors(i) 返回的平均数,它可以使平均 big-O 不同。

关于算法的算法分析(big-O),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15233803/

相关文章:

java - Java 中一组数据的排列

c# - 使用缓冲区从折线获取多边形

algorithm - 分而治之 - 为什么它有效?

arrays - PowerShell:数组表示法之间的区别?

ms-access - VBA 和 MS-Access 中的 Bang 表示法和点表示法

java - 在调车场保留括号

java - 反向然后添加序列 : Big-O runtime of my solution?

c++ - 我无法找到这些代码段的 Big O 表示法

objective-c - Objective-c 点符号或方括号符号中首选什么?

algorithm - 2个运动物体的碰撞算法