Professional Documents
Culture Documents
CS312 Lecture3
CS312 Lecture3
CS312 Lecture3
of Algorithms
(CS312x)
• We shouldn’t ignore
asymptotically slower
algorithms, however.
• Real-world design
situations often call for a
T(n) careful balancing of
engineering objectives.
• Asymptotic analysis is a
useful tool to help to
n n0 structure our thinking.
Insertion sort analysis
Worst case: Input reverse sorted.
n
T(n)= ∑ Θ(j)=Θ(n 2 ) [arithmetic series]
j=2
Average case: All permutations equally likely.
n
T(n)= ∑ Θ(j / 2)=Θ ( n 2)
j=2
1
Merging two sorted arrays
20 12 20 12
13 11 13 11
7 9 7 9
2 1 2
1
Merging two sorted arrays
20 12 20 12
13 11 13 11
7 9 7 9
2 1 2
1 2
Merging two sorted arrays
20 12 20 12 20 12
13 11 13 11 13 11
7 9 7 9 7 9
2 1 2
1 2
Merging two sorted arrays
20 12 20 12 20 12
13 11 13 11 13 11
7 9 7 9 7 9
2 1 2
1 2 7
Merging two sorted arrays
20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11
7 9 7 9 7 9 9
2 1 2
1 2 7
Merging two sorted arrays
20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11
7 9 7 9 7 9 9
2 1 2
1 2 7 9
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11
7 9 7 9 7 9 9
2 1 2
1 2 7 9
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11
7 9 7 9 7 9 9
2 1 2
1 2 7 9 11
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11 13
7 9 7 9 7 9 9
2 1 2
1 2 7 9 11
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11 13
7 9 7 9 7 9 9
2 1 2
1 2 7 9 11 12
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11 13
7 9 7 9 7 9 9
2 1 2
1 2 7 9 11 12
Θ(1)
Recursion tree
Solve T(n) = 2T(n/2) + cn, where c > 0 is constant.
cn
c cn/2
h = lg n cn/4 cn/4 cn/4
n/2
cn/4
Θ(1)
Recursion tree
Solve T(n) = 2T(n/2) + cn, where c > 0 is constant.
cn cn
c cn/2
h = lg n cn/4 cn/4 cn/4
n/2
cn/4
Θ(1)
Recursion tree
Solve T(n) = 2T(n/2) + cn, where c > 0 is constant.
cn cn
c cn/2 cn
h = lg n cn/4 cn/4 cn/4
n/2
cn/4
Θ(1)
Recursion tree
Solve T(n) = 2T(n/2) + cn, where c > 0 is constant.
cn cn
c cn/2 cn
h = lg n cn/4 cn/4 cn/4 cn
n/2
cn/4
Θ(1)
Recursion tree
Solve T(n) = 2T(n/2) + cn, where c > 0 is constant.
cn cn
c cn/2 cn
h = lg n cn/4 cn /4 cn/4 cn
n/2
cn/4
Θ(1) #leaves = n Θ(n)
Recursion tree
Solve T(n) = 2T(n/2) + cn, where c > 0 is constant.
cn cn
c cn/2 cn
h = lg n cn/4 cn /4 cn/4 cn
n/2
cn/4
Θ(1) #leaves = n Θ(n)
Total = Θ(n lg n)
Conclusions
• Θ(n lg n) grows more slowly than Θ(n ).
2
Number of Number of
Comparisons Comparisons
by Sequential by Binary
Array Size Search Search
128 128 8
1,024 1,024 11
1,048,576 1,048,576 21
4, 294, 967, 296 4, 294, 967, 296 33
The Fibonacci Sequence
F0=0
F1=1
Fn=Fn-1+Fn-2 where n>1
F2= F1+F0
F3= F2+F1
int fib (int n)
{
if (n <= 1)
return n;
else
return fib (n - 1) + fib (n-2);
}
The Fibonacci Sequence
n Number of Terms
Computed
0 1
1 1
2 3
3 5
4 9
5 15
6 25
The Fibonacci Sequence
Show recursion Tree from the e book