Algorithms Course 10 Prune and Search 2 Outlines

  • Slides: 11
Download presentation
演算法課程 (Algorithms) Course 10 削減與搜尋 Prune and Search

演算法課程 (Algorithms) Course 10 削減與搜尋 Prune and Search

2 ▓ Outlines u 本章重點 n n n Prune and Search概念 A Simple Example:

2 ▓ Outlines u 本章重點 n n n Prune and Search概念 A Simple Example: 二分搜尋法 挑選第k小的元素 (kth Selection) 問題

7 u 如何挑選p? n 將n個元素區分成 5個一組,分行存放。若最後一組元素不足 5個, 則以 補足 n 把每一組由小到大排序,每組第三大元素即是組中位數M n 選p為所有組中位數 (有

7 u 如何挑選p? n 將n個元素區分成 5個一組,分行存放。若最後一組元素不足 5個, 則以 補足 n 把每一組由小到大排序,每組第三大元素即是組中位數M n 選p為所有組中位數 (有 個) 的中位數 (by recursive call) At least 1/4 of S known to be less than or equal to P. Each 5 -element subset is sorted in nondecreasing sequence. P M At least 1/4 of S known to be greater than or equal to P.

8 演算法 u Input: A set S of n elements. u Output: The kth

8 演算法 u Input: A set S of n elements. u Output: The kth smallest element of S. n Step 1: 將 S 分成 n/5 組資料集合,每一組有5個資料,不足 5個 資料以 補足。 n Step 2: 排序每一組資料 n Step 3: 找出所有組中位數的中位數 n Step 4: 將S區分成三部份S 1, S 2 and S 3, which contain the elements less than, equal to, and greater than p, respectively. n Step 5: 利用三個判斷條件以找出第k小的元素: ¡ If |S 1| k , then 第k小的元素存在於 S 1,prune away S 2 and S 3。 ¡ else, if |S 1| + |S 2| k, k then p即為第k小的元素。 小的元素 ¡ else, 第k小的元素存在於S 3中,prune away S 1 and S 2。令k’ = (k |S 1| - |S 2|),在 S 3中找第k’個元素即為解答. |)

9 範例 u. S = {1, 25, 2, 24, 3, 23, 4, 22, 5,

9 範例 u. S = {1, 25, 2, 24, 3, 23, 4, 22, 5, 21, 6, 20, 7, 19, 8, 18, 9, 17, 10, 16, 11, 15, 12, 14, 13},找第k小的元素。 Ans [Step 1] [Step 2] 1 25 2 24 3 23 4 22 5 21 6 20 7 19 8 18 9 17 10 16 11 15 12 14 13 1 2 3 24 25 4 5 21 22 23 6 7 8 19 20 9 10 16 17 18 11 12 13 14 15

10 [Step 3] [Step 4] : S 1 : S 2 : S 3

10 [Step 3] [Step 4] : S 1 : S 2 : S 3 1 2 3 24 25 4 5 21 22 23 6 7 8 19 20 9 10 16 17 18 11 12 13 14 15 1 6 11 2 7 12 3 8 13 24 19 14 25 20 15 [Step 5] 利用三個判斷條件以找出第k小的元素 n 若 k = 11 (搜尋範圍 |S 1|) n 若 k = 13 (搜尋範圍 |S 1|+ |S 2|) n 若 k = 22 (搜尋範圍 |S 3|) 9 4 10 5 16 21 17 22 18 23

11 Time complexity u At least n/4 elements are pruned away. u The problem

11 Time complexity u At least n/4 elements are pruned away. u The problem remaining in step 5 contains at most 3 n/4 elements. u Time complexity: T(n) = O(n) n step 1: O(n) //掃一輪即可得知 n step 2: O(n) //有 n/5 組資料,每組資料排序需固定常數時間O(1) n step 3: T(n/5) //採遞迴方式找尋,共有 n/5 組 n step 4: O(n) //掃一輪即可得知 n step 5: T(3 n/4) //每次Prune掉至少n/4資料量後,尚有3 n/4左右的剩餘資料 需遞迴執行 u 遞迴方程式為T(n) = T(3 n/4) + T(n/5) + O(n),採遞迴樹法分析,可得知 此演算法的時間複雜度為 O(n)