1.algorithm and Complexity
1.algorithm and Complexity
Asymptotic notation
& Complexity
A l g o r i t h m A n a l ys i s
• Algorithms can be evaluated on two
performance measures
• Time taken to run an algorithm
• Memory space required to run an algorithm
• …for a given input size
arrayMax(A,n)
Max=A[0]
for i=1 to n-1 do
If Max < A[i] then Max = A[i]
Return Max
Pseudo Code
• More structured and less formal
• Expressions
– Standard Math symbols (numeric/boolean)
• Method Declarations
– Algorithm name(param1,param2)
Pseudo Code
• Programming Constructs:
– If … then …else
– While-loop
– for-loop
– Array : A[i]; A[I,j]
• Methods
– Calls: method(args)
– Returns: return value
Analysis of Algorithms
• Analyze time taken by Primitive Operations
• Low level operations independent of
programming language
– Data movement (assign..)
– Control (branch, subroutine call, return…)
– Arithmetic/logical operations (add, compare..)
3,
0
end
Estimated time for A[n][n] = (n(n-1)/2).(3+2) + 2.n
Is this constant for a given ‘n’?
Asymptotic Analysis
• Goal: to simplify analysis of running time
by getting rid of ‘details’ which may be
affected by specific implementation and
hardware.
– Like ‘rounding’: 1001 = 1000
– 3n2=n2
• How the running time of an algorithm
increases with the size of input in the limit.
– Asymptotically more efficient algorithms are
best for all but small inputs.
Asymptotic Notation: “Big O”
TB, Sahni
• O Notation
– Asymptotic upper bound
– f(n)=O(g(n)), if there exists
constants c and n0, s.t. c.g(n)
A Better A l go r i t h m
s=0
for i=0 to n do
s = s + X[i]
A[i] = s/(i+1)
end
return A