CS109A Notes For Lecture 1/31/96 Measuring The Running Time of Programs Example
CS109A Notes For Lecture 1/31/96 Measuring The Running Time of Programs Example
Structure Trees
Example:
(1)
(2)
(3)
(4)
(5)
main() {
int i;
scanf("%d", &i);
while(i>0) {
putchar('0' + i%2);
i /= 2;
}
putchar('\n');
}
Block
1{5
1
While
2{4
Block
3{4
3
But we must include O(1) for the increment and test each time around the loop.
The possibility that the loop is executed
0 times must be considered. Then, O(1)
for the initialization and rst test is the
total cost.
Example: Consider binary-conversion function.
Size of data = i.
Lines 1, 3, 4, 5 each O(1) by the basis.
Block of 3{4 is O(1) + O(1) = O(1).
While of 2{4 iterates at most log2 i times.
Bound on body times number of iterations =
O(1) log2 i = O(log i).
Block of 1{5 is O(1) + O(log i) + O(1) =
O(log i).
i.e., it takes O(log i) time to convert i to binary by this function.
for
1{5
block
2{5
while
3{5
block
4{5
4