Given the sequence of numbers: 5, 4, 3, 2, 1, we intend to sort them into ascending order.
A. How many swaps does it take to sort this sequence via Insertion sort? (4 points)
B. How many recursive calls does it take by the Merge sort to get the job done? (4 points)
C. How many times the partition procedure will be called by the Quicksort to do the same job? (4 points)
A. 完全反向,第 \(i\) 個元素要往前換 \(i-1\) 次(每次 swap 消去一個 inversion)
\(1+2+3+4=10\)(\(=\binom52\))次
B. MergeSort(l, r) 在 \(l\lt r\) 時再呼叫兩次
[5,4,3,2,1] → [5,4,3]、[2,1](2 次);[5,4,3] → [5,4]、[3];[2,1] → [2]、[1](4 次);[5,4] → [5]、[4](2 次)
遞迴呼叫 \(2+4+2=8\) 次(遞迴樹共 9 個節點,最外層的原始呼叫不算遞迴呼叫)
C. 以最後一個元素(或第一個)當 pivot,長度 \(\ge2\) 的區間才會呼叫 partition
[5,4,3,2,1] → pivot 1,剩 [4,3,2,5](1 次);[4,3,2,5] → pivot 5,剩 [4,3,2](2 次);[4,3,2] → pivot 2,剩 [3,4](3 次);[3,4] → pivot 4(4 次)
partition 共呼叫 4 次(此輸入對這種 pivot 是 worst case)
A. 10;B. 8(含最外層共 9 次呼叫);C. 4