我正在完成我的课程作业,这部分内容涉及对几个for循环的运行时间进行“分析”。教练指定他想要一个Big Oh Notation答案。这些for循环的大O符号是什么?
我对总运行时间的基础上建立的依据是:
1)The cost of executing each statement
2)The frequency of execution of each statement
3)The idea of working from "inside and out", specifically starting from inner loops.
我知道:
total = 0;
for (int i = 0; i < n;i++){
total++;
}
答:O(N)的运行线。
for (int i = 0; i < n;++i)
for (int j = 0; j < n;++j)
total++;
答案:O(N^2),我们只关心N有多大的增长。
我很困惑的
for (int i = 0;i < n;++i)
for (j=0;j < n * n;++j)
++total;
和
for (i = 0;i < n;++i)
for (j = 0; j < i;++j)
++total;
最后但并非最不重要的,我从我的课本,所有的三重嵌套循环都为N^3运行时间假设?
第一个以O(n^3)运行,第二个以O(n^2)运行 – Ra1nWarden
这些循环非常简单,您可以通过实验获得它。你可以尝试不同的'n'值(循环)并推导出订单。例如尝试n = 10和n = 20,看看'total'的比例是多少。 –
更确切地说,最后一个是'=(n *(n-1))/ 2 =(n^2 -n)/ 2'O(n^2)' – Rocki