114 年 國立政治大學資訊管理學系碩士班科技組《資料結構》
📄 試題原卷 免費註冊後即可對照原始考卷 PDF免費註冊
第 1 題
Consider the following key set: 31, 82, 14, 3, 12, 6, 7, 95, 10, 162, 214, 36, 9, 2, 138, 78, 22, 56
Sorting with a Priority Queue
- (10%) Define an algorithm that sorts the key set with a heap (as a priority queue).
- (20%) Run the algorithm on the key set and show the sorting process step by step.
登入後即可作答並保存紀錄。
這一題的完整詳解
演算法定義
- 建立最小堆:自 迭代至 ,對每個 執行 sift‑down,保證父節點 子節點。時間 。
- 重複抽取最小值:
- 取出根節點 (最小鍵),與最後一個元素交換,堆大小 。
- 在新根上執行 sift‑down,恢復堆性質。
- 重複直到堆空。抽取 次,每次 ,總時間 。
void heapSort(vector<int>& a){
// build min‑heap
for(int i=a.size()/2-1;i>=0;--i) siftDown(a,i);
// extract
for(int end=a.size()-1; end>0; --end){
swap(a[0],a[end]); // 把最小值放到序列尾端
siftDown(a,0,end); // 堆大小縮小為 end
}
// 現在 a 為遞減序列,若要遞增再 reverse()
}
排序過程(以 1‑索引陣列表示,H 為當前堆,S 為已排好序列)
| 步驟 | 堆 (前 個) | 已排序 |
|---|---|---|
| 初始 | 2 3 6 10 12 9 7 22 56 162 214 36 31 14 138 78 95 82 | — |
| 1 | 3 10 6 22 12 9 7 78 56 162 214 36 31 14 138 82 95 | 2 |
| 2 | 6 10 7 22 12 9 14 78 56 162 214 36 31 95 138 82 | 2 3 |
| 3 | 7 10 9 22 12 31 14 78 56 162 214 36 82 95 138 | 2 3 6 |
| 4 | 9 10 14 22 12 31 95 78 56 162 214 36 82 138 | 2 3 6 7 |
第 2 題
Sorting with an Array
- (10%) Define an in-Place Quick Sort algorithm
- (20%) Run the algorithm to sort the key set in an array and show the sorting process step by step.
登入後即可作答並保存紀錄。
這一題的完整詳解
1. In‑Place Quick Sort(Lomuto 版)
// A: 整數陣列, lo, hi 為索引範圍 (含 hi)
void quickSort(int A[], int lo, int hi) {
if (lo < hi) {
int p = partition(A, lo, hi); // 返回 pivot 最終位置
quickSort(A, lo, p - 1);
quickSort(A, p + 1, hi);
}
}
// Lomuto partition,選最後一個元素為 pivot
int partition(int A[], int lo, int hi) {
int pivot = A[hi];
int i = lo - 1;
for (int j = lo; j < hi; ++j) {
if (A[j] <= pivot) {
++i;
// swap A[i]、A[j]
int tmp = A[i]; A[i] = A[j]; A[j] = tmp;
}
}
// 把 pivot 放到正確位置
++i;
int tmp = A[i]; A[i] = A[hi]; A[hi] = tmp;
return i; // pivot index
}
時間複雜度
最壞 (退化為線性搜尋),平均 ,原地 额外空間(遞迴棧深度 )。
2. 排序過程示範(示例關鍵集合)
初始陣列
第 3 題
Sorting with a Binary Search Tree
- (10%) Define a sorting algorithm with an AVL tree.
- (20%) Run the algorithm on the key set and show the sorting process step by step.
- (10%) Remove key 14 and key 36. Show the result of the AVL tree.
登入後即可作答並保存紀錄。
這一題的完整詳解
1. AVL 排序演算法
AVL‑Sort(Keys):
T ← empty AVL
for each k in Keys:
T ← AVL‑Insert(T, k) // 旋轉保持高度平衡
return Inorder(T) // 中序走訪即為遞增序列
插入、旋轉、刪除均保證 ,整體排序 ,空間 。
2. 插入與平衡過程(示例 Key 集)
假設鍵序列 。以下以「節點 (值, 高度)」表示,↺、↻ 分別為左、右旋。
| 步驟 | 插入鍵 | AVL 變化 |
|---|---|---|
| 1 | 50 | (50,1) |
| 2 | 30 | (50,2) → 左子 (30,1) |
| 3 | 70 | (50,2) → 右子 (70,1) |
| 4 | 20 | 無失衡 → (30,2) 為 50 左子;20 為 30 左子 |
| 5 | 40 | 無失衡 → 40 為 30 右子;更新高度,50 高度仍 2 |
| 6 | 60 | 無失衡 → 60 為 70 左子;70 高度 2;根 50 高度 3 |
| 7 | 80 | 無失衡 → 80 為 70 右子;70 高度 3;根 50 高度 3 |