Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Example-Prefix Sums

In this section, we will determine a tight big-oh bound on the running time of a program to compute the series of sums tex2html_wrap_inline60349, tex2html_wrap_inline60305, ..., tex2html_wrap_inline58691, where

displaymath60347

An algorithm to compute this series of summations is given in Program gif. Table gif summarizes the running time calculation.

   program1924
Program: Program to compute tex2html_wrap_inline60355 for tex2html_wrap_inline60357

 

 

statement time
3a O(1)
3b tex2html_wrap_inline60361
3c tex2html_wrap_inline60361
5 tex2html_wrap_inline60361
6a tex2html_wrap_inline60361
6b tex2html_wrap_inline60369
6c tex2html_wrap_inline60369
7 tex2html_wrap_inline60369
8 tex2html_wrap_inline60361
TOTAL tex2html_wrap_inline59179
Table: Computing the running time of Program gif

Usually the easiest way to analyze program which contains nested loops is to start with the body of the inner-most loop. In Program gif, the inner-most loop comprises lines 6 and 7. In all, a constant amount of work is done--this includes the loop body (line 7), the conditional test (line 6b) and the incrementing of the loop index (line 6c).

For a given value of j, the inner-most loop is done a total j+1 times. And since the outer loop is done for tex2html_wrap_inline60383, in the worst case, the inner-most loop is done n times. Therefore, the contribution of the inner loop to the running time of one iteration of the outer loop is O(n).

The rest of the outer loop (lines 3, 5 and 8) does a constant amount of work in each iteration. This constant work is dominated by the O(n) of the inner loop. The outer loop is does exactly n iterations. Therefore, the total running time of the program is tex2html_wrap_inline59179.

But is this a tight big oh bound? We might suspect that it is not, because of the worst-case assumption we made in the analysis concerning the number of times the inner loop is executed. The inner-most loop is done exactly j+1 times for tex2html_wrap_inline60383. However, we did the calculation assuming the inner loop is done O(n) times, in each iteration of the outer loop. Unfortunately, in order to determine whether our answer is a tight bound, we must determine more precisely the actual running time of the program.

However, there is one approximate calculation that we can easily make. If we observe that the running time will be dominated by the work done in the inner-most loop, and that the work done in one iteration of the inner-most loop is constant, then all we need to do is to determine exactly the number of times the inner loop is actually executed. This is given by:

eqnarray1950

Therefore, the result tex2html_wrap_inline60401 is a tight, big-oh bound on the running time of Program gif.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.