Algorithms (112 01) Ch2
Algorithms (112 01) Ch2
of ECE, TKU
Fall, 2023
Chapter 2
Recurrence
• A recurrence is an equation (or inequality) that
describes a function in terms of its values on
smaller inputs
• Cost model
T(n) = (1), if n c
T(n) = D(n) + aT(n/b) + C(n), otherwise
• a, b, and c are constants
• D(n) is the cost (time) for dividing the problem into a
subproblems with 1/b size of the original one
• C(n) is the cost (time) for combining the solutions to the
subproblems into the solutions to the original problem
© 2023 by Jiann-Chyi Rau Algorithms 2-2
Dept. of ECE, TKU
Fall, 2023
Divide-and-Conquer (DC)
• Divide the problem into a number of
subproblems that are smaller instances of
the same problem
• Conquer the subproblems by solving them
recursively
– If the subproblem sizes are small enough (base
cases), solve them in a straightforward manner
• Combine the solutions to the subproblems
into the solution for the original problem
// sentinel card in L
// sentinel card in R
p q q+1 r
L R
(c) (d)
(e) (f)
© 2023 by Jiann-Chyi Rau Algorithms 2-8
Dept. of ECE, TKU
Fall, 2023
(g) (h)
(i)
Problem:逆序對數
• 給一數列a1, a2, ..., an,請設計一個O(nlgn)
演算法去求它的逆序對數,即有多少個有
序對(i, j),使得i < j且 ai > aj。
– 提示:Merge Sort
H impossible!!
counterexample
θ(1)
Divide θ(1)
T(n/2)
Conquer T(n/2)
θ(n)
Combine θ(1)
Ai+Ai+1+…+Aj = Sj – Si-1
– O(n)
Matrix Multiplication
• Input: Two n x n (square) matrices, A = (aij)
and B = (bij)
• Output: n x n matrix C = (cij) where C = AB
• Brute-force algorithm
– T(n) = Θ(n3)
C11=P5+P4-P2+P6
C21=P3+P4
C22=P5+P1-P3-P7
Substitution
• Upper bound
• Lower bound
• Tight bound
Recursion Tree
• Each node represents cost of a single
subproblem
– E.g. T(n) = T(n/3) + T(2n/3) + cn
(2/3)kn = 1
k = log3/2n
Master Theorem
– f(n) = (nlog 2)
2