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

Average Running Times

 

In the previous section, we found the function, tex2html_wrap_inline58401, which gives the running time of Program gif as a function both of number of inputs, n, and of the actual input values. Suppose instead we are interested in a function tex2html_wrap_inline58409 which gives the running time on average for n inputs, regardless of the values of those inputs. In other words, if we run Program gif, a large number of times on a selection of random inputs of length n, what will the average running time be?

We can write the sum of the running times given in Table gif in the following form

  equation533

where tex2html_wrap_inline58415 is the probability that line 6 of the program is executed. The probability tex2html_wrap_inline58415 is given by

displaymath58403

I.e., tex2html_wrap_inline58415 is the probability that the tex2html_wrap_inline58387 array entry, tex2html_wrap_inline58389, is larger than the maximum of all the preceding array entries, tex2html_wrap_inline58425.

In order to determine tex2html_wrap_inline58415, we need to know (or to assume) something about the distribution of input values. For example, if we know a priori that the array passed to the function FindMaximum is ordered from smallest to largest, then we know that tex2html_wrap_inline58429. Conversely, if we know that the array is ordered from largest to smallest, then we know that tex2html_wrap_inline58431.

In the general case, we have no a priori knowledge of the distribution of the values in the input array. In this case, consider the tex2html_wrap_inline58387 iteration of the loop. In this iteration tex2html_wrap_inline58389 is compared with the maximum of the i values, tex2html_wrap_inline58425 preceding it in the array. Line 6 of Program gif is only executed if tex2html_wrap_inline58389 is the largest of the i+1 values tex2html_wrap_inline58445. All things being equal, we can say that this will happen with probability 1/(i+1). Thus

  eqnarray549

Substituting this expression for tex2html_wrap_inline58415 in Equation gif and simplifying the result we get

  eqnarray555

where tex2html_wrap_inline58451, is the tex2html_wrap_inline58453 harmonic number .


next up previous contents index

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