08b Analyzing Iterative Constructs
08b Analyzing Iterative Constructs
Analyzing if statements
if(<condition>)
<then part>
else <else part>
Evaluation
of condition takes a constant number of
primitive operations
Assume if-part has upper bound
Assume else-part has upper bound
If-else example
if(A[1][1] == 0)
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
A[i][j]=0;
else
for(int i=0; i<n; i++)
A[i][i] = 0;
How often
is this block
executed?
Complex Loops
Some loops do not specify explicitly how
many times the loop body is executed
10
The
11
12
Example [1]
main(){
int a, n;
scanf("%d", &n);
a = foo(0,n);
printf("%d",
bar(a,n));
}
Example [2]
main(){
int a, n;
scanf("%d", &n);
a = foo(0,n);
printf("%d",
bar(a,n));
}
int foo(int x, int n){
for(int i=1; i<=n; i++)
x += bar(i,n);
return x;
}
foo
mai
n
bar
14
Example [3]
main(){
int a, n;
scanf("%d", &n);
a = foo(0,n);
printf("%d",
bar(a,n));
}
foo
bar
O(n)
15
Example [4]
main(){
int a, n;
scanf("%d", &n);
a = foo(0,n);
printf("%d",
bar(a,n));
}
O(n2)
foo
bar
O(n)
16
Example [5]
main(){
int a, n;
scanf("%d", &n);
a = foo(0,n);
printf("%d",
bar(a,n));
}
bar
O(n)
17
Summary
Primitive operations are considered to have a
constant running time.
Analyzing simple loops makes use of the number
of iterations and the cost of the loop body.
To analyze complex loops the worst case may
need to be assumed.
Analyzing conditional statement involves using
the worst case.
Non-recursive functions can be analyzed
independently.
18