Lecture 2 DC
Lecture 2 DC
Lecture 2 DC
Παναγιώτης Χ. Πετραντωνάκης
Επίκουρος Καθηγητής
Τμήμα Ηλεκτρολόγων Μηχ. & Μηχ. Υπολογιστών
ppetrant@ece.auth.gr
• Combine answers
• At the end of the recursion where the subproblems are small and are solved
outright
𝑥 = 𝑥𝐿 + 𝑥𝑅
𝑛
𝑥= 𝑥𝐿 22 + 𝑥𝑅
and
𝑛
𝑦= 𝑦𝐿 22 + 𝑦𝑅
𝑛 𝑛
𝑥𝑦 = 𝑥𝐿 22 + 𝑥𝑅 𝑦𝐿 22 + 𝑦𝑅 =
𝑛
= 2𝑛 𝑥𝐿 𝑦𝐿 + 22 𝑥𝐿 𝑦𝑅 + 𝑥𝑅 𝑦𝐿 + 𝑥𝑅 𝑦𝑅
𝑛 𝑛
𝑥𝑦 = 𝑥𝐿 22 + 𝑥𝑅 𝑦𝐿 22 + 𝑦𝑅 =
𝑛
= 2𝑛 𝑥𝐿 𝑦𝐿 + 22 𝑥𝐿 𝑦𝑅 + 𝑥𝑅 𝑦𝐿 + 𝑥𝑅 𝑦𝑅
𝑇 𝑛 = 4𝑇 𝑛ൗ2 + 𝑂(𝑛)
Divide and Conquer 7
# of steps
Recursive Calls 𝑐𝑛 = 20 𝑐𝑛
𝑛 4
4𝑐 = 𝑐𝑛 = 2𝑐𝑛
2 2
. . . 𝑛 42
16𝑐 = 𝑐𝑛 2 = 4𝑐𝑛
4 2
. . . 𝑛 43
64𝑐 = 𝑐𝑛 3 = 8𝑐𝑛
8 2
. . .
. . .
4𝑘
𝑐𝑛 𝑘 = 2𝑘 𝑐𝑛
2
2𝑘+1 −1
• 1 + 21 + 22 + ⋯ + 2𝜅 = = 2log2 𝑛+1 − 1 = 2 ∙ 2log2 𝑛 − 1 =
2−1
2𝑛 − 1
2𝑘+1 −1
• 1 + 21 + 22 + ⋯ + 2𝜅 = = 2log2 𝑛+1 − 1 = 2 ∙ 2log2 𝑛 − 1 =
2−1
2𝑛 − 1
𝑎 + 𝑏𝑖 𝑐 + 𝑑𝑖 = 𝑎𝑐 − 𝑏𝑑 + 𝑏𝑐 + 𝑎𝑑 𝑖
𝑎 + 𝑏𝑖 𝑐 + 𝑑𝑖 = 𝑎𝑐 − 𝑏𝑑 + 𝑏𝑐 + 𝑎𝑑 𝑖
𝑏𝑐 + 𝑎𝑑 = 𝑎 + 𝑏 𝑐 + 𝑑 − 𝑎𝑐 − 𝑏𝑑
𝑛
𝑥𝑦 = 2𝑛 𝑥𝐿 𝑦𝐿 + 22 𝑥𝐿 𝑦𝑅 + 𝑥𝑅 𝑦𝐿 + 𝑥𝑅 𝑦𝑅 =
𝑛
= 2𝑛 𝑥𝐿 𝑦𝐿 + 22 𝑥𝐿 + 𝑥𝑅 𝑦𝐿 + 𝑦𝑅 − 𝑥𝐿 𝑦𝐿 − 𝑥𝑅 𝑦𝑅 + 𝑥𝑅 𝑦𝑅
Thus:
𝑛
𝑇 𝑛 = 3𝑇 + 𝑂(𝑛)
2
Divide and Conquer 15
# of steps
Recursive Calls 𝑐𝑛 = 20 𝑐𝑛
𝑛 3
3𝑐 = 𝑐𝑛
2 2
. . . 𝑛 32
9𝑐 = 𝑐𝑛 2
4 2
. . . 𝑛 33
27𝑐 = 𝑐𝑛 3
8 2
. . .
. . .
3𝑘
𝑐𝑛 𝑘
2
log2 𝑛 log2 3
= 3𝑐3log2 𝑛 = 3𝑐 2log2 3 = 3𝑐 2log2 𝑛 = 3𝑐𝑛log2 3
log2 𝑛 log2 3
= 3𝑐3log2 𝑛 = 3𝑐 2log2 3
= 3𝑐 2log2 𝑛
= 3𝑐𝑛log2 3
𝑛
• Theorem: if 𝑇 𝑛 = 𝑎𝑇 + 𝑂 𝑛𝑑 , for 𝑎 > 0, 𝑏 > 1, 𝑑 ≥ 0 then:
𝑏
𝑂 𝑛𝑑 𝑖𝑓 𝑑 > log 𝑏 𝑎
𝑇 𝑛 = 𝑂 𝑛𝑑 log 𝑏 𝑛 𝑖𝑓𝑑 = log 𝑏 𝑎
𝑂 𝑛log𝑏 𝑎 𝑖𝑓 𝑑 < log 𝑏 𝑎
𝑛
• Algorithm: Comprare 𝑘 with Depending on the
𝑧[ ].
2
result recurse either on the first or the second
half of 𝑧.
• 𝑎 =? , 𝑏 =? , 𝑑 =?
• Running time=?
9 1 5 4 7 11 2 6
CLRS
CLRS
𝑇 𝑛 = 𝑛 𝑛 𝑛
= 𝑐1 𝑛 + 𝑐2 𝑛 − 1 + 𝑐4 𝑛 − 1 + 𝑐5 𝑡𝑗 + 𝑐6 (𝑡𝑗 − 1) + 𝑐7 (𝑡𝑗 − 1)
𝑗=2 𝑗=2 𝑗=2
+ 𝑐8 (𝑛 − 1)
• Then:
𝑇 𝑛 = 𝑐1 𝑛 + 𝑐2 𝑛 − 1 + 𝑐4 𝑛 − 1 + 𝑐5 𝑛 − 1 + 𝑐8 𝑛 − 1 = 𝑂(𝑛)
• All 𝑡𝑗 = 𝑗 (have to compare key with all elements on its left, 𝑗 − 1 elements)
𝑛 𝑛+1
• We know: σ𝑛𝑗=2 𝑡𝑗 = σ𝑛𝑗=2 𝑗 = σ𝑛𝑗=1 𝑗 − 1 = −1
2
• Thus:
𝑇 𝑛 = 𝑂(𝑛2 )
𝑛
• 𝑇 𝑛 = 𝑎𝑇 + 𝑂(𝑛𝑑 )
𝑏
𝑛
• 𝑇 𝑛 = 𝑎𝑇 + 𝑂(𝑛𝑑 )
𝑏
• 𝑎 = 2, 𝑏 = 2
𝑛
• 𝑇 𝑛 = 𝑎𝑇 + 𝑂(𝑛𝑑 )
𝑏
• 𝑎 = 2, 𝑏 = 2, 𝑑 = 1.
𝑂 𝑛𝑑 𝑖𝑓 𝑑 > log 𝑏 𝑎
• 𝑇 𝑛 = 𝑂 𝑛𝑑 log 𝑏 𝑛 𝑖𝑓𝑑 = log 𝑏 𝑎
𝑂 𝑛log𝑏 𝑎 𝑖𝑓 𝑑 < log 𝑏 𝑎
• 𝑇 𝑛 = 𝑛 log 𝑛
Recursive Calls 𝑐𝑛
𝑛
2𝑐 = 𝑐𝑛
2
𝑛
4𝑐 = 𝑐𝑛
4
. . . 8𝑐
𝑛
8
= 𝑐𝑛
. . .
. . .
𝑛
. . . log 𝑛 𝑐
log 𝑛
= 𝑐𝑛
CLRS
• The depth of the tree is the worst case complexity of the algorithm
• The depth of the tree is the worst case complexity of the algorithm
• Thus
𝑛
𝑑
𝑛 2 𝑛 𝑛
2 ≥ 𝑛! → 𝑑 ≥ log 𝑛! ≥ log = log
2 2 2
Ερωτήσεις;
Ανάλυση και Σχεδιασμός Αλγορίθμων
Divide and Conquer