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

Yet Another Example-Finding the Largest Element of an Array

In this section we consider the problem of finding the largest element of an array. That is, given an array of n non-negative integers, tex2html_wrap_inline57597, we wish to find

displaymath57589

The straightforward way of solving this problem is to perform a linear search  of the array. The linear search algorithm is given in Program gif and the running times for the various statements are given in Table gif.

   program524
Program: Linear search to find tex2html_wrap_inline57599.

 

 

statement time
5 tex2html_wrap_inline57473
6a tex2html_wrap_inline57415
6b tex2html_wrap_inline57605
6c tex2html_wrap_inline57607
7 tex2html_wrap_inline57609
8 tex2html_wrap_inline57611
9 tex2html_wrap_inline57415
Table: Computing the running time of Program gif.

With the exception of line 8, the running times follow simply from Axioms gif, gif and gif. In particular, note that the body of the loop is executed n-1 times. This means that the conditional test on line 7 is executed n-1 times. However, the number of times line 8 is executed depends on the data in the array and not just n.

If we consider that in each iteration of the loop body, the variable result contains the largest array element seen so far, then line 8 will be executed in the tex2html_wrap_inline57621 iteration of the loop only if tex2html_wrap_inline57623 satisfies the following

displaymath57590

Thus, the running time of Program gif, tex2html_wrap_inline57533, is a function not only of the number of elements in the array, n, but also of the actual array values, tex2html_wrap_inline57597. Summing the entries in Table gif we get

displaymath57591

where

eqnarray558

While this result may be correct, it is not terribly useful. In order to determine the running time of the program we need to know the number of elements in the array, n, and we need to know the values of the elements in the array, tex2html_wrap_inline57597. Even if we know these data, it turns out that in order to compute the running time of the algorithm, tex2html_wrap_inline57635, we actually have to solve the original problem!


next up previous contents index

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