15
BASICS 2 Prof. Michael Tsai 2012/3/6 Office hour 改改改 9-10 改改 改改改改改改改改改 ! 改改改改改 !

BASICS 2

Embed Size (px)

DESCRIPTION

Office hour 改成 三 9-10. BASICS 2. Prof. Michael Tsai 2012/3/6. 作業一的程式題不容易寫呀 ! 要趕快開始 !. Definition [Omega ]: { : there exist positive constants and such that for all } “f of n is omega of g of n ” 可以想成是 Lower Bound. Asymptotic notation – Omega. since for all 1 . - PowerPoint PPT Presentation

Citation preview

Page 1: BASICS 2

BASICS 2Prof. Michael Tsai2012/3/6

Office hour 改成三 9-10

作業一的程式題不容易寫呀 !要趕快開始 !

Page 2: BASICS 2

2

Asymptotic notation – Omega

• Definition [Omega]:• {: there exist positive constants and such that for all }

• “f of n is omega of g of n”

• 可以想成是 Lower Bound

Page 3: BASICS 2

3

Examples

• since for all 1.

• since for all 1.

• since for all .

• since for all 1.

• since for all 1.

for all

Page 4: BASICS 2

4

Examples• (1)• (1)

for all

Page 5: BASICS 2

5

Discussion• Omega is a lower bound.• Should be as large a function as possible.

• Theorem: If and , then .

• ( 證明 : 請自己證證看 !)

Page 6: BASICS 2

6

Asymptotic Notation – Theta• Definition [Theta]:

{: there exist positive constants such that for all }

• “f of n is theta of g of n”• 三明治夾心 , 同時具有和

Theta Platform

GMC Terrain

Page 7: BASICS 2

7

用圖表示• Big Oh• 紅色• Omega• 藍色• Theta• 紅色藍色都要

Page 8: BASICS 2

8

Example

• since for all and for all .

for all

Page 9: BASICS 2

9

Discussion• More precise than both the “big oh” and omega notations• It is true if and only g(n) is both an upper and lower bound on f(n).• Coefficient = 1• (no good)• (ok!)

• Theorem: If and , then .• ( 證明 : 請自己證證看 !)

Page 10: BASICS 2

10

那麼 , 怎麼知道程式的時間複雜度 ?• 看每個 statement 執行幾次 , 畫表來計算• 有時候複雜度不只跟 input 大小不一定有關係• ( 像是 binary search, 跟裡面實際數字是什麼有關 )• 這時候可以取• Worst case: 給一組 input 可以使此 algorithm 執行最慢 ; 最慢的

執行時間是多少 ?• Best case: 給一組 input 可以使此 algorithm 執行最快 ; 最快的

執行時間是多少 ?• Average case: 考慮所有 case 的執行時間 , 平均是多少 ?

• 實際測量程式執行時間最實際 !• ( 但是常常不可行 , 此時 asymptotic analysis 是最好的

方法 )

Page 11: BASICS 2

11

Example 1Statement Asymptotic complexity

void add(int a[][MAX_SIZE]…) { 0

int i,j; 0

for(i=0;i<rows;i++)

for(j-0;j<cols;j++)

c[i][j]=a[i][j]+b[i][j];

} 0

Total

Page 12: BASICS 2

12

Example 2int binsearch(int list[], int searchnum, int left, int right) {

int middle;while(left<=right) {

middle=(left+right)/2;switch(COMPARE(list[middle], searchnum)) {

case -1: left=middle+1; break;case 0: return middle;case 1: right=middle-1;

}}return -1;

}

Page 13: BASICS 2

13

1 3 4 4 6 7 11 13 13 13 18 19

0 1 2 3 4 5 6 7 8 9

searchnum=13;

left rightmiddle

middle=(left+right)/2;

left=middle+1;

10 11

Half the searching window every iteration.

Worst case: Best case:

Page 14: BASICS 2

14

兜基 ??

Θ(𝑛)Θ(𝑛2)𝑛2ms106𝑛𝑚𝑠

Page 15: BASICS 2

15

哪一個好…

• n 很大的時候右邊比左邊好

• 但是 n 會很大嗎 ?• 有時候不會• 如果 n 永遠小於 ??• 結論 : 要看 n 大小 ( 實際上寫程式的時候適用 )

Θ(𝑛)Θ(𝑛2)𝑛2ms106𝑛𝑚𝑠