CNG213 Lecture 2 - Algorithm-Analysis
CNG213 Lecture 2 - Algorithm-Analysis
• Information:
– 100 Miles
• Knowledge :
– 100 Miles is a quite far distance
Information
CNG 213 - Lecture 2 6/55
Data Information Knowledge
Information
Knowledge
CNG 213 - Lecture 2 7/55
What is Data Structure?
• A data structure is a way of storing data in a
computer so that it can be used efficiently.
– It is an organisation of mathematical and logical
concepts of data.
– Space complexity:
– Data structures take space…
– What kind of data structures can be used?
– How does the choice of data structure affect the runtime?
• To analyze algorithms:
– First, we start to count the number of significant operations in a particular
solution to assess its efficiency.
– Then, we will express the efficiency of algorithms using growth functions.
Generality!!!
• E.g.:
– Make an addition = 1 operation
– Calling a method or returning from a method = 1 operation
– Index in an array = 1 operation
– Comparison = 1 operation etc.
Cost Times
if (n < 0) c1 1
absval = -n c2 1
else
absval = n; c3 1
• The most important thing to learn is how quickly the algorithm’s time
requirement grows as a function of the problem size.
30/55
CNG 213 - Lecture 2
Running times for small inputs
Running time
Upper bound
lower bound
• f(N) = O(g(N))
• Thus, the algorithm requires no more than c*n2 time units for
n n0 , so it is O(n2) 37
CNG 213 - Lecture 2 37/59
Big-Oh: Examples
• “n² + 3n + 4” is O(n²) f(N) = O(g(N))
if and only if there are
positive constants c and n0
– since n² + 3n + 4 < 2n² for all n > 10
such that
f(N) c g(N) when N n0
• “n3 + 3n + 4” is O(n3)
• 1 + 4N = O(N)
• sin N = O(1)
• 10 = O(1)
• 1010 = O(1)
• log N + N = O(N)
O(N)
• Nested loops
– The running time of the statement multiplied by the product of
the sizes of all the loops.
O(N2)
CNG 213 - Lecture 2 41/59
General rules (cont’d)
• Consecutive statements
– These are just adds.
• If Statement
If S1 Else S2
• Now, we have to solve this recurrence equation to find the growth-rate function of
hanoi-towers algorithm.
T(n) = 2*T(n-1) + c
= 2 * (2*T(n-2)+c) + c
= 2 * (2* (2*T(n-3)+c) + c) + c
= 23 * T(n-3) + (22+21+20)*c (assuming n>2)
when substitution repeated i-1th times
= 2i * T(n-i) + (2i-1+ ... +21+20)*c
when i=n
= 2n * T(0) + (2n-1+ ... +21+20)*c
= 2n * c1 + ( )*c
= 2n * c1 + ( 2n-1 )*c = 2n*(c1+c) – c So, the growth rate function is
O(2n)
int fact(int n)
{
if (n ==0)
return (1);
else
return (n * fact(n-1));
}