資料結構與演算法(使用Python、ZeroJudge)
零、學習資料結構與演算法的目的
1. 資料結構討論「資料儲存的方式」
2. 演算法討論「解決問題的想法」
:mega: 所選用的資料結構和演算法將影響程式的複雜度與效率
3.參考網站
一、資料結構
1. 堆疊
- LIFO(last in first out)
- 串列模擬堆疊(Stack)常用的方法
串列方法(函式) |
意義 |
len(sk) |
回傳串列個數 |
sk.append(x) |
將 x 附加到串列後面 |
sk.pop() |
回傳最後一個元素並刪除 |
- 模擬程式
EX_1_1:執行下列堆疊程式,印出一堆堆疊操作後的堆疊內容。
2. 佇列
- FIFO(first in first out)
- 串列模擬佇列(Queue)常用的方法
串列方法(函式) |
意義 |
len(q) |
回傳串列個數 |
q.append(x) |
將 x 附加到串列後面 |
q.pop(i) |
回傳索引值i的元素,並將其刪除; 如果沒有i,則傳回最後一個元素並刪除 |
- 模擬程式
EX_1_2:執行下列佇列程式,印出一堆佇列操作後的佇列內容。
3. 樹
-
模擬具有樹枝狀性質的資料,由節點與邊組成,例如家族族譜、電腦資料夾結構。
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
-
二元樹
-
二元樹的走訪(Tree Traversal)(課本p4-7)
EX_1_3:下圖的前序、中序、後序走訪分別為?
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
EX_1_4:建立二元搜尋樹
依讀入順序 30, 15, 50, 35, 10, 25, 40, 20, 45 建立一個二元搜尋樹(binary search tree)。
EX_1_5:若一篇文章每個字母出現的次數為:a:8,b:7,c:3,d:4,e:5。
建立Huffman Tree(次數小的結點放左邊),並求每個字母的Huffman Code。
a->11
b->
c->
d->
e->00
4. 圖
EX_1_6:下圖的DFS與BFS走訪順序為(子節點以字母序走訪)?
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
DFS: 將走訪順序標示在字母「上」。
線條以「黑色箭頭」代表往下探尋,以「白色箭頭」代表回溯上一個點。
BFS: 將階層編號(紅色)標示在字母「下」。
- 圖的應用1-最小生成樹(minimum spanning tree)(課本p5-23)
- Kruskal演算法為一個使用貪婪法 (greedy method) 的演算法,一開始為一空樹,每次在不讓圖中含有任何迴路(cycle)下尋找圖中最小權重的邊加入樹中,直到所有點皆在樹中即完成。
- Prim演算法與Dijkstra演算法類似,屢次找出不在樹上,離樹最近的點。
EX_1_7:畫出下圖的最小生成樹,其權重總和為?28
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
EX_1_8:畫出下圖的相鄰陣列,以Dijkstra演算法,求A到各點的最短路徑(以Excel表格表示)?0 8 6 4 3 1 5
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
二、演算法
1. 演算法效能
-
運算能力
- 費式數列-遞迴 vs. 陣列
- 搜尋-循序 vs. 二分搜尋
-
時間複雜度
-
大O記號(Big-O notation)
- 令f(n) 與g(n) 是由非負整數對應至實數的函數,若存在正實數常數c 和正整數常數n0,使n≧n0時,f(n) ≦ cg(n) 成立,則我們說 f(n)=O(g(n))。
- 若f(n)=3n2+2,g(n)=n2 (n0=2, c=4)。f(n)=O(n2)

2.求質數演算法效能比較
3. 排序(sort)
4. 二分搜尋(binary search)
5. 分而治之(Divid and Conquer)