Design and Analysis of Algorithm Decrease and Conquer Algorithm
第一章 演算法分析 Algorithm Analysis
description
Transcript of 第一章 演算法分析 Algorithm Analysis
朝陽科技大學資管系 李麗華
第一章 演算法分析
Algorithm Analysis
The early bird gets the worm.
--李麗華 資料結構講義
練功前的沉思Q1: 過去曾操作過某些軟體,其功能雷同, 但為什麼執行起來,花費的時間差異很大?Q2: 以前班上有些同學寫程式看起來很厲害,但是 他們寫的程式內容真的很棒的嗎??Q3:我在資訊領域中學會了撰寫程式,但同樣一隻 程式 ,大家寫出來的內容都不太一樣,那我如何 知道我的程式寫的好不好,有沒有方法可以評量?
(*)資料結構 (DS)就是這個基礎入門功夫 ,DS協助我們 釐清 ,如何撰寫一隻程式(或演算法),了解資料本 身如何影響一個演算法的優劣
--李麗華 資料結構講義
What is algorithm
Definition: ( 以後簡稱 Def)
An algorithm is a finite set of instructions that , if followed, accomplishes a particular task.
定義 :
演算法就是利用有限的步驟來解決特定的問題 .
--李麗華 資料結構講義
Characteristics of an Algorithm
-All algorithm must have:
(1) Input: zero or more quantities supplied externally
(2) Output: at least one quantity is produced
(3) Definiteness: clear and unambiguous
(4) Effectiveness: easy to carry out
(5) Finiteness: for all cases, the algorithm terminates
--李麗華 資料結構講義
How to measure an algorithm?
所以說 , 一支解決特定問題的程式 , 其實就是一個解決特定問題的 algorithm.
那程式寫的好不好 , 到底如何量測 ?? 要量什麼 ?
(1) 測量執行的時間 (time)
(2) 測量程式內每個 statement 被執行的次數(3) 測量程式所須耗用的空間 (memory space)
Complexity Analysis即在分析演算法時 , 我們運用上述各項測量方式來分析程式的效能 .
Time Complexity: 程式執行時所花的時間分析
--李麗華 資料結構講義
敘述執行次數說明程式分析 1: 陣列內元素相加
執行次數
int sum(int arr[], int n){ int i, total=0; for(i=0; i<n; i++) total += arr[I]; return total;}
1
1 n+1
1n
---------2n+4
程式分析 2: 二元陣列相乘
執行次數
void mul(int a[][], int b[][], int c[][], int n){ int i,j,k,sum; for(i=0; i<n; i++) for(j=0; j<n; j++) { sum=0; for(k=0; k<n; k++) sum=sum+a[i][k]*b[k][j] c[i][j]=sum; }}
1
1
n+1n(n+1)
n2
n2(n+1)n3
N2
1------------2 n3 +4 n2 +2n+3
--李麗華 資料結構講義
Big-O 又是什麼 ?在分析演算法時 , 每個個程式敘述被執行的次數稱為 order of magnitude, 亦稱為 Big-O.
Big-O 的定義為 : 若 f(n) 此函數代表一個程式敘述須要被執行的總次數 , 如果可以找到 g(n),i.e., f(n)<= cg(n) for all n, & c:constant, 則 f(n)=O(g(n))
f(n)=amnm+am-1nm-1+…+a1n1+a0 , 則 f(n)=O(nm) ( 請參見課本證明 )
--李麗華 資料結構講義
Big-O 範例說明 Examples:
4n + 2 O(n)7n - 3 O(n)200n + 6 O(n)10n2 + 5n - 2 O(n2)9n3- n2 + 5n - 5 O(n3)7*2n + n3 + n2 O(2n)
:
--李麗華 資料結構講義
常見的 Big-O 及其優劣O(1): constant time
O(log n): sub-linear time
O(n): linear time
O(n log n): n log n time
O(n2): quadratic time
O(n3): cubic time
O(2n): exponential time
O(n!): factorial time
這 .. 這也太不可思議了…
這演算法真的太優了…
好棒的演算法……… 這仍然令人激賞…… ..
well, 算是大眾化囉… .
嗯…該用點心了… .
天那 , 指數 ? 太不妙了…
我哭 , 真的沒輒了嗎 ?
優
劣
--李麗華 資料結構講義
Plot of Big-O Performance ( 參見 P13)
--李麗華 資料結構講義
Time needed for various time complexity ( 參見 P13)
--李麗華 資料結構講義
Times on a 1 billion instruction per second computer(p.40)
--李麗華 資料結構講義
大師—該動動腦囉 !!
課本第一章習題 , 請解答下列 : 第 3 題 ( 全部 ): 將程式列出並在右邊寫出對照的執行次數 , 最後並找出加總次數及正確的 Big-O 值
第 4 題 : 如題目所要求 , 列出當 X=1,3,13,21 時 ,在 while 迴圈內所須要執行的次數 , 及所有加總次數
第 5 題 : 將程式列出 , 並在右邊寫出對照的執行次數 , 最後並找出加總次數及正確的 Big-O 值
(*) 本次作業以紙本繳交
--李麗華 資料結構講義
Now there is no time to think of
what you do not have.
Think of what you can do with what there is.
與其懊腦所失 , 不如掌握現在--Earnest Hemingway(1899-1961)