Is this big O notation correct for this c++ code?

亡梦爱人 提交于 2020-12-30 04:41:12

问题


currently I have best case as o(n), worst case as o(n). I am unsure if this is correct for the following code segment and I would really appreciate if someone could confirm it is correct, or explain why it's wrong. Thanks!

template<typename T>
void vector_print(const T& vector, bool repeat)
{
    for (typename T::size_type i = 0; i < vector.size(); ++i)
    {
        for (typename T::size_type j = 0; j < vector.size(); ++j)
        {
            std::cout << vector[j] << ",";
        }
        std::cout << std::endl;

        if (!repeat) {
            break;
        }
        repeat = !repeat;
    }
}

回答1:


The outer loop is never going to be executed more than twice, so you've got O(2*vector.size()), which reduces to O(vector.size()).

So your answer seems correct to me.



来源:https://stackoverflow.com/questions/65067167/is-this-big-o-notation-correct-for-this-c-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!