Escolar Documentos
Profissional Documentos
Cultura Documentos
C
Computational
i
lC
Complexity
l i
COL 100 - Introduction to Computer
p
Science
II Semester 2015-2016
Department of Computer Science and Engineering
Indian Institute of Technology Delhi
Portable
P t bl across computers
t
Can be used as a sub-program
Jan 2016
Efficiency of Algorithms
Algorithms/Programs evaluated in terms
of:
execution time
memory space
Jan 2016
Identifying Redundant
Computation
Redundant
computation
can be moved
from loop
loop invariant
loop-invariant
computation
Jan 2016
x = 0;
0
for (i = 0; i < 10; i++) {
y = (a*a*a + c)*x*x + (b*b)*x + c;
cout << y;
x = x + 0.01;
}
x = 0;
t1 = (a*a*a + c);
t2 = b*b;
for (i = 0; i < 10; i++) {
y = t1*x*x
1* * + t2*x
2* + c;
cout << y;
x = x + 0.01;
}
P. R. Panda, IIT Delhi
Early
l Termination
Searching in array:
break when found
Jan 2016
Computational Complexity
Quantitative measure of algorithms performance
needed
independent of programming language
independent of machine
y = ax2 + b
y = ax + b
y = log x
Jan 2016
Asymptotic Analysis
What happens for large n?
Jan 2016
Order Notation
Function g(n) is of order O(f(n)) if
there exists c for which g(n) cf(n)
for all n some n1
Jan 2016
10
Why use O(
O( ) for measuring
Complexity?
p
y
Hiding constants
crude/approximate
easier to compute
holds across machines
Jan 2016
11
int main () {
...
max = -10000;
for (i = 0; i < n; i++)
if (max < a[i])
max = a[i];
}
Total operations = 1 + 2n
Worst Case Complexity is O(n)
Best Case?
Average
g Case?
Jan 2016
12
Efficient Algorithms
Problem:
Given real number x and integer n
Write an algorithm to calculate xn
Jan 2016
13
First Algorithm
Power
power(x,n) = 1 for n = 0
power(x, n) = x * power(x,n-1) for n>1
float prod = 1.0;
for ((int i = 0;; i < n;; i++))
prod = prod * x;
Jan 2016
14
Efficient Algorithm
Fast Power
fpower(x,n) = 1 for n = 0
fpower(x,n) = x * (fpower(x, n/2))2 if n is odd
fpower(x,n) = (fpower(x, n/2))2 if n is even
What is the
complexity
p
y
of this algorithm?
Jan 2016
15
Searching in an Array
Given array A[N] and value V, is V
present in the Array? 0 1 2 3
A
fo nd = false;
found
for (i = 0; i < N; i++)
if (A[i] == V) {
found = true; // V is present
break;
}
Jan 2016
H many comparisons?
i
?
How
best case
average case
worst case
16