Professional Documents
Culture Documents
Analysis
Unit 1
CPRG304 – Object-Oriented
Programming III
• Example: Concat.java
Experimental Analysis
• Benchmarking for running time
long start = System.currentTimeMillis();
// run algorithm
long stop = System.currentTimeMillis();
time = stop – start;
• Example: b3 = b x b x b
b2 = b x b
b1 = b
b0 = 1
Dusting off some Mathematics
• Logarithms: Given a positive number y, the logarithm of
y to the base of 2 (log2 y) is the number of copies of 2
that must be multiplied together to equal y
• Example: log2 1 = 0
log2 2 = 1
log2 4 = 2
log2 8 = 3
Logarithms
• Another way to look at logs:
log2 8 : 8/2 = 4
4/2 = 2
2/2 = 1
• 8 divided by base 2, exactly 3 times, to get to 1
• The same applies to all base values
• E.g. log5 125 = 3
20 = 1 <
21 = 2 < 3 <
22 = 4 < 5 < 6 < 7 <
23 = 8 < 9 < 10 < 11 < 12 < 13 < 14 < 15 <
24 = 16 < 17 < 18 etc.
Pattern of Logarithms
• Mathematically, this is represented as:
Log2 (any number n) = m if: 2m <= n < 2m+1
Solving for m: m <= log2 n < m+1
m = floor(log2 n)
• Note: Any divide and conquer algorithm will have this log2 n
for input size n!
Algorithm Analysis
• First we need a high-level description of the algorithm
to analyze
• Recall: Algorithm = step-by-step procedure
• f(n) = 9(floor(log2 n) + 1) + 3
Comparing the Power Algorithms
multiplications
simple power
algorithm
smart power
algorithm
n
Growth Rates
• Actual times taken by algorithms is great, but we are
more interested in the growth rate for each algorithm
• As we increase the input size, the running time will also
increase
• How much increase (the change in running time) is the most
important part of algorithm analysis!
• E.g. Simple vs. Smart
3. 7 log2n
4. 21000
Common Growth Rates in Big O
• O(1) constant
• O(log n) logarithmic
• O(n) linear
• O(n log n) linearithmic
• O(n2) quadratic
• O(n3) cubic
• O(nk), k>1 polynomial
• O(2n), n>1 exponential
• O(n!), n>1 factorial
Comparing the Growth Rates
2n n2
n log n
• Ultimately we want to
know which algorithm is
“better”?
1. for each n {
// some code
}
2. for each n {
for each n {
// some code
}
}
Cumulative Time Complexity
• Suppose that an algorithm consists of 2 steps,
performed in sequence:
• Step 1’s time complexity is O(n)
• Step 2’s time complexity is O(n2)
2. For each n {
For each n {
// 5 operations
}
}
• 5n2 = O(n2)