05 Analysis of Algorithms
05 Analysis of Algorithms
05 Analysis of Algorithms
Analysis of Algorithms
Acknowledgement
The contents of these slides have origin from
School of Computing, National University of
Singapore.
We greatly appreciate support from Mr. Aaron
Tan Tuck Choy, and Dr. Low Kok Lim for
kindly sharing these materials.
2
Policies for students
These contents are only used for students
PERSONALLY.
Students are NOT allowed to modify or
deliver these contents to anywhere or anyone
for any purpose.
3
Objectives
Book
• Chapter 10: Algorithm Efficiency
and Sorting, pages 529 to 541.
Terminat
Exact
e
Effective General
A comparison of algorithms
Should focus on significant differences in the efficiency
of the algorithms
Should not consider reductions in computing costs
due to clever coding tricks. Tricks may reduce the
readability of an algorithm.
Computers
Data
Problem size
Total Ops = A + B
f(n) is said to be
bounded from c*g(n)
above by g(n).
O() is called the f(n)
“big O” notation.
g(n)
n0
26
O(1): câu lệnh gán, điều kiện, công thức tính
toán
Quy tắc cộng: dành cho những câu lệnh cùng
cấp, độ phức tạp của nó là giá trị max.
Quy tắc nhân: dành cho những khối lệnh
lồng với nhau
27
4.2 Ignore the coefficients of all terms
Based on the definition, 2n2 and 30n2 have the
same upper bound n2, i.e.,
2n2 = O(n2)
Why?
30n2 = O(n2)
Note:
“log” = log base 2, or log2; “log10” = log base 10; “ln” = log
base e. In big O, all these log functions are the same.
(Why?)
[501043 Lecture 11: Analysis of Algorithms]
31
4.6 Examples on big O notation
f1(n) = ½n + 4
= O(n)
f2(n) = 240n + 0.001n2
= O(n2)
f3(n) = n log n + log n + n log (log n)
= O(n log n)
Why?
:
After i iterations, at most n/2i are left
Best-Case Analysis
Interested in the best-case behaviour
Not useful
Average-Case Analysis
A determination of the average amount of time that an algorithm
requires to solve problems of size n
Have to know the probability distribution
The hardest
CompareRunningTimes2.java CompareRunningTimes3.java
int x = 0;
int x = 0; // Triply nested loop
// Doubly nested loop for (int i=0; i<n; i++) {
for (int i=0; i<n; i++) { for (int j=0; j<n; j++) {
for (int j=0; j<n; j++) { for (int k=0; k<n; k++) {
x++; x++;
} }
} }
[501043 Lecture 11: Analysis of Algorithms] } 56
6.1 Compare Running Times (3/3)
Single Doubly Triply
n loop nested Ratio nested Ratio
O(n) loop O(n2) loop O(n3)
100 0 2 29
200 0 7 7/2 = 3.5 131 131/29 = 4.52
400 0 12 12/7 = 1.71 960 7.33
800 0 17 17/12 = 1.42 7506 7.82
1600 0 38 38/17 = 2.24 59950 7.99
3200 1 124 124/38 = 3.26 478959 7.99
6400 1 466 3.76
12800 2 1844 3.96
25600 4 7329 3.97
51200 8 29288 4.00
ai = 1; c = 1/3
Hence sum = 1/(1 – 1/3) = 3/2
[501043 Lecture 11: Analysis of Algorithms]
59
End of file