简体   繁体   English

最坏情况下的运行时间Big O

[英]Worst-case running time Big O

Could you please explain how I can get the worst-case Big O of this algorithm. 您能否解释一下如何获得该算法的最坏情况BigO。 I was reading my textbook and I came across a similar algorithm like this one but still don't understand the logic behind it. 我在读教科书时遇到了类似的算法,但仍然不了解其背后的逻辑。

int t=0;
for(int x=0;x<num.length;x++){
    for(int y=0;y<num.length;y++){
        for(int p=0;p<num.length;p++){
            for(int w=0;w<num.length;w++){
                if(num[p][w]>num[x][y])
                {
                    t=num[x][y];
                    num[x][y]=num[p][w];
                    num[p][w]=t;
                }
            }
        }
    }
} 

The logic is pretty simple. 逻辑很简单。 Let's start with the most inner loop: 让我们从最内部的循环开始:

This loop runs num.length times. 此循环运行num.length次。 Its worst case runtime complexity in big-O notation is O(n) assuming n = num.length . 假设n = num.length它在big-O表示法中最差的运行时复杂度是O(n)

for(int w=0;w<num.length;w++){
    ...
}

Now when you put another for-loop around it of length p , it will run the above for-loop p times. 现在,当您在长度为p周围放置另一个for循环时,它将运行上述for循环p次。 So it is O(pn) . 所以它是O(pn) In your case, p = num.length = n so it should be O(n*n) = O(n^2) . 在您的情况下, p = num.length = n因此应为O(n*n) = O(n^2)

There are 4 nested loops in your example so the answer is O(n^4) . 您的示例中有4个嵌套循环,因此答案为O(n^4)

Why did I ignore the content of the most inner loop? 为什么我忽略最内部循环的内容? Because there are a constant number of operations done, let that number be c . 因为完成的操作数量恒定,所以将该数量设为c Asymptotic analysis used by the big-O notation says the following: O(c) is equivalent to O(1) . big-O表示法使用的渐近分析表示: O(c) is equivalent to O(1) That comes from the definition of big-O . 那来自big-O定义

If you are comparing an element for; 如果您正在比较一个元素; == or < or > against a list or an array of size n, Then its worst case is O(n). ==或<或>对大小为n的列表或数组,则其最坏情况是O(n)。

Therefore the cost of one for loop is: O(n), but you have 4 for loops each with a worst case O(n). 因此,一个for循环的成本为:O(n),但您有4个for循环,每个循环的最坏情况为O(n)。

Total cost is: n*n*n*n = Worst Case O(n^4). 总成本为:n * n * n * n =最坏情况O(n ^ 4)。

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

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