第二章 Big O notation 進階課程,bignotation
第二章
Big O notation 進階課程
在這一章中,我們將會瞭解到演算法的基礎----Counting primitive operation,什麼是primitive operation:
The following are all primitive operations:
1. Assigning a value to a variable
2. Calling another algorithm (function)
3. Performing an arithmetic operation (adding, etc)
4. Indexing into an array
5. Comparing two values (includes all logical and relational
6. operators)
7. Following (dereferencing) an object reference (pointer)
8. Returning from a method (function, procedure)
舉一個例子:
currentMax <-A[0] 2 ops
i <-1 1 op
while (i < n) do 1 op
if ( currentMax < A[i] ) 2 ops
then currentMax Ω A[i] 2 ops
i <- i + 1 2 ops
done
return currentMax 1 op
Loop Body:
Single loop body iteration: 5 or 7 operations
Loop body repeated n -1 times.
So: between 5(n -1) and 7(n-1) operations, when n > 1
Best case: t = 2 + 1 + 5(n - 1) + 1 = 5n -1
Worst case: t = 2 + 1 + 7(n - 1) + 1 = 7n -3
舉一個我們學校的例子吧
在這裡我們可以看到在這兩個方程中,想得到big O 的話,我們需要將內外兩個loop的big O相乘
而第一個例子會變成從一到n-1的累加,而結果是n(n-1)/2
在這裡我放上一個講解比較優秀的網站連結,大家如果感興趣可以看一下的:
http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/
另外給大家幾道試題做,大家試試看,下期我會公布答案,並且詳細的解答。