我正在完成我的課程作業,這部分內容涉及對幾個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