gpt4 book ai didi

algorithm - 如何计算算法的运行时间

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:15 24 4
gpt4 key购买 nike

我有以下算法:

for(i = 1; i < n; i++){ 
SmallPos = i;
Smallest = Array[SmallPos];
for(j = i + 1; j <= n; j++)
if (Array[j] < Smallest) {
SmallPos = j;
Smallest = Array[SmallPos];
}
Array[SmallPos] = Array[i];
Array[i] = Smallest;
}

这是我的计算:

For the nested loop, I find a time complexity of
1 ("int i = 0") + n+1 ("i < n") + n ("i++")
* [1 ("j = i + 1") + n+1 ("j < n") + n ("j++")]
+ 3n (for the if-statement and the statements in it)
+ 4n (the 2 statements before the inner for-loop and the final 2 statements after the inner for-loop).
This is (1 + n + 1 + n)(1 + 1 + n + n) + 7n = (2 + 2n)(2 + 2n) + 7n = 4n^2 + 15n + 4.

但不幸的是,教科书得到了T(n) = 2n^2 +4n -5。拜托,有人愿意向我解释我哪里错了吗?

最佳答案

这里是用数学方式(Sigma 表示法)表示您的算法的正式方式:

enter image description here

用外循环中的操作数替换c,用内循环中的操作数替换c'

关于algorithm - 如何计算算法的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17327241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com