Recursive - Ch04
Recursive - Ch04
Chapter 2: Fundamentals of
the Analysis of Algorithm
Efficiency
Mathematical Analysis of Non-recursive and Recursive Algorithms
2
Example: Selection sort 1
■ Input: An array A[0..n-1]
■ Output: Array A[0..n-1] sorted in ascending order
for i ← 0 to n-2 do
min ← i
for j = i + 1 to n – 1 do
if A[j] < A[min]
min ← j
swap A[i] and A[min]
3
Example: Selection sort 2
■ Basic operation: comparison
Inner loop:
n-1
S(i) = Σ 1 = (n-1) – (i + 1) + 1 = n – 1 – i
j = i+1
Outer loop:
n-2 n-2 n-2 n-2
C(n) = Σ S(i) = Σ (n – 1 – i) = Σ (n – 1) – Σ i
i=0 i=0 i=0 i=0
n
Basic formula: Σi = n(n+1) / 2
i=0
C(n) = (n – 1 )(n -1 ) – (n-2)(n-1)/2 = (n – 1) [2(n – 1) – (n – 2)] / 2 =
= (n – 1) n / 2 = O(n2)
4
Section 2.4. Mathematical
Analysis of Recursive Algorithms
Steps in mathematical analysis of non-
recursive algorithms
n! = n*(n-1)! Telescoping:
0! = 1 T(n) = T(n-1) + 1
T(n-1) = T(n-2) + 1
Recurrence T(n-2) = T(n-3) + 1
relation: …
T(2) = T(1 ) + 1
T(n) = T(n-1) + 1
Add the equations and cross equal
T(1) = 1 terms on opposite sides: