如何在此循环操作计数中找到此迭代的数量

How to find the number of iteration in this while loop - operation count

本文关键字:迭代 循环 操作      更新时间:2023-10-16

我对如何进行操作计数一段时间循环我感到困惑。我确实了解如何找到常规循环(从0到n(以及二进制搜索(log2n(的迭代数量,但是此代码利用了True和False的情况。迭代的数量将取决于"更多"是否为true,而"找到"是错误的。

最坏的情况是什么?找不到项目?在下面的代码中,注释的零件是该行的操作计数。

列表是n个节点的链接列表结构:

void FindItem(Node *list, Item item, Node *&loc, bool &found){
    bool more = true;                 // 1
    loc = list; found = false;        // 2
    while (more && !found) {          // (number of iterations)
        if (item < loc->info)         // 2 * (number of iteration)
            more = false;             // (0 or 1)*number of iterations
        else if (item == loc->info)   // 2 * (number of iteration)
            found=true;               // (0 or 1)*number of iterations
        else {
            loc = loc->next;          // (0 or 2) * (number of iteration)
            more = (loc != NULL);     // (0 or 2)*number of iterations
        }
    }
}

这看起来像学校练习或家庭作业问题。您需要在纸上回答的事实几乎证实了这一点。

因此,您要寻找的可能是"大O"的复杂性。在那种情况下,您正在查看一个简单的0 .. n循环,您声称自己知道,因为最多可以在整个列表上运行。

条件变量more的名称及其自我的条件清楚地表明,代码不过是在排序列表上的linier搜索。