



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




















In comparing two di erent implementations of the same ADT, an imp ortant question to address is their relative execution times. It might app ear, at rst, that describing the execution time of a computer algorithm should b e easy. One merely runs the algorithm with a stopwatch in hand (or any numb er of technological variations of a similar theme) and records the results. And indeed, such a value, called a benchmark, is o ccasionally useful. We will examine b enchmarks later in this chapter.
Most of the time, however, a b enchmark is not a go o d characterization of a computer algorithm. A b enchmark only describ es the actual p erformance of a program on a sp eci c machine on a given day. Di erent pro cessors can have dramatically di erent p erformances (computer manufacturers go to great lengths to remind users of this fact in hop es of entic- ing them to purchase faster and more costly machines). Even working on a single machine, there may b e a selection of many alternative compilers for the same programming language. These compilers will pro duce slightly di erent machine co de instructions for the same source language, and thus have varying execution times. Finally, execution timings for multipro- cessing computers (computers that can p erform many tasks simultaneously) will b e altered by the other tasks b eing p erformed at the same time.
In this chapter we intro duce the concept of algorithmic analysis (or analysis of algo- rithms), a technique used to characterize the execution b ehavior of algorithms in a manner indep endent of a particular platform, compiler, or language. Many of the data structures describ ed in this b o ok provide similar functionality, but di er in their execution times for various op erations. Thus, selecting the appropriate typ e of container for any particular problem involves not only an understanding of a container's capabilities, but also an under- standing of how execution times are determined and contrasted.
Rather than measuring the execution time of computer programs, we will henceforth sp eak of measuring computer algorithms. An algorithm will generally b e emb o died in one or more metho ds. Thus, our measurements will b e based on an examination of the execution time for the invo cation of a single metho d. Of course, making individual metho ds faster can only help to improve the execution sp eed of entire programs. We would like a technique to abstract away small variations, and describ e the p er- formance of algorithms in a more idealized, pro cessor-indep endent fashion. It is clear that alternative approaches for the same problem can have dramatically di erent execution times. Ask yourself, for example, why dictionaries list words in alphab etical order. The reason, we know, is that doing so p ermits the reader to discover a word by rep eatedly moving back and forth over increasingly smaller sections of the b o ok (a pro cess we will later lab el bi- nary search). If dictionaries were not ordered, then to discover whether a particular word app eared in the collection the reader would have to examine the list in sequence from one end to the other, comparing the test word against each entry in turn; obviously this pro cess would b e considerably slower than nding a word in a normal dictionary. The technique we use to capture this more-or-less intuitive notion of complexity is an idea called algorithmic analysis. In algorithmic analysis (sometimes termed asymptotic analysis) we gain p ower by, ironically, losing precision. By systematically ignoring constant amounts, and instead concentrating on an abstract characterization of the size of a problem, we can make more intelligent comparisons. Determining whether a word app ears in an unorganized list of n alternatives requires, for example, comparing each word against the target, and therefore uses approximately n comparisons. We assume each of these comparisons can b e p erformed in a constant amount of time (the particular constant is unimp ortant, b eing greater or smaller dep ending up on
unknown constant c. On the other hand, if the list is ordered and we can easily move to any p osition in the collection we will see (later in this chapter) that the search can b e p erformed
unknown value d. Because the actual constants involved are unknown and, largely, irrelevant, we can elim- inate them from our description. We use a notation, called \big-Oh" notation, which cap- tures this intuitive idea. We say that searching an unorganized list requires O (n) steps (read \big-Oh of n steps"), whereas searching a sorted and randomly accessible dictionary can b e p erformed in O (log n) steps (read \big-Oh of log n steps"). We call the big-Oh characterization the asymptotic execution time for the op eration. The formal de nition of big-Oh states that if f (n) is a function that represents the actual execution time of an algorithm, then the algorithm is O (g (n)) if, for all values n larger than some xed constant n 0 , there exists some constant c, such that f (n) is always b ounded by
of critical imp ortance to theoreticians, an intuitive feeling for algorithmic execution is of
return Color.red; else return Color.black;
Even when pro cedures are quite lengthy, if they do not include lo ops or pro cedure calls, then the total execution time must remain constant.
A lo op that p erforms a constant numb er of iterations is still considered to b e executing in constant time. An example might b e the following, which creates a deck of playing cards, and places them into an array:
int topCard = 0;
cards[topCard++] = new Card(Card.diamond, i); cards[topCard++] = new Card(Card.club, i); cards[topCard++] = new Card(Card.spade, i); cards[topCard++] = new Card(Card.heart, i);
private Card [ ] cards = new Card[52]; ...
Such lo ops, however, are relatively rare in comparison to lo ops in general. More com- monly, the numb er of iterations a lo op will p erform is determined in some fashion by the input values. To describ e the running time of a lo op we need to characterize how many iterations the lo op will p erform, and then multiply this value by the running time of the b o dy of the lo op. The simplest case o ccurs when the limits of the lo op are xed by the input value, and the b o dy of the lo op uses constant time. An example in which this o ccurs is a pro cedure that takes as arguments a array of values and returns the smallest value in the collection:
// pre: values has at least one element // p ost: returns smallest value in collection int n = values.length; double minValue = values[0];
The array is the only data structure provided by the Java language that is de- signed sp eci cally to hold a collection of values. (Other data structures are provided by the standard Java library, but they are not part of the basic Java language). While many computer languages have an array data typ e, the array in Java is slightly more general than most. For example, when declaring a variable as an array the programmer need not sp ecify an upp er b ound. This can b e seen, for example, in the declaration of command line arguments that must b e present in the main pro cedure in any program:
...
The square brackets signify that args is an array of String values, yet do not sp ecify how many elements the array will hold. Instead, the size of an array is established when the value of the variable is rst created. Here, to o, Java is di erent than most other computer languages. In Java creating an array is a two step pro cess. First, the variable that will hold the array must b e declared. Second, the space for the variable must b e allo cated using the new op erator. This can b e seen in the CardDeck example: Card [ ] cards = new Card[52]; // create an array with 52 elements Values in an array are accessed using the subscript op erator. The index values used with this op erator must b e greater than equal to zero, and less than the numb er of elements in the array. Again, Java is unlike some other languages (such as C++) in that index b ounds are checked, and an exception will b e raised if they are not valid.
As noted earlier, the execution time of a lo op is the numb er of iterations of the lo op multi- plied by the execution time for the b o dy of the lo op. This b ecomes more complex for nested lo ops. The simplest case o ccurs when the limits of the lo ops are indep endent of one other. In this situation, the execution time is the pro duct of the values representing the numb er of times each lo op will iterate multiplied by the execution time of the b o dy. An example of this is the classic algorithm for multiplying two n by n matrices, to pro duce a new n by n matrix pro duct.
int n = a.length;
c[i][j] = 0.0;
The numb er of iterations in each lo op is n. The b o dy of the innermost lo op, which p erforms only a multiplication, an addition, and an assignment, is constant time. Therefore the total running time is O (n^3 ). A more complex analysis is required when the limits of iteration for the inner lo ops are linked to an outer lo op. An example of this b ehavior is found in the pro cedure bubbleSort, which places the values of an array into sorted order. An outer lo op provides the index for the value to b e placed. An inner lo op then compares elements against each other, \bubbling" larger elements to the top of the array. By the end of each iteration of the inner lo op the largest remaining value will have b een moved into p osition.
int n = v.length; // nd the largest remaining value // and place into v[i]
// move large values to the top
double temp = v[j]; // then swap v[j] = v[j + 1]; v[j + 1] = temp;
To determine the running time of this pro cedure we can simulate execution on a few values. The pattern that quickly b ecomes apparent is that on the rst iteration of the
Mathematical Induction
called mathematical induction. We will encounter mathematical induction (or induction, for short) in many di erent places and guises in our investigations of data structures, and thus it is useful to b e well versed in the technique. To apply mathematical induction one rst forms a hypothesis, a statement of the result you think will hold. In this case, our hyp othesis will b e that the sum of the values from 1 to n is given by the formula n(n 2 +1). Discovering a hyp othesis is sometimes the most dicult part of a mathematical induction pro of. Sometimes the hyp othesis will b e provided for you naturally in the problem statement; other times it can only b e discovered by, for example, lo oking for patterns in several di erent cases. The next step is to verify this formula for one or more base cases. If we select 1 for n, for example, we have 1 for the sum, and 22 for the fraction, so the result holds. If we select 2 for n, we have 3 for the sum, and 2 2 3 for the fraction, so the result again holds. The nal step is to verify the formula for all remaining integers. We do this by assuming the hyp othesis holds for all integers smaller than or equal to some indeterminate value n, then proving it must therefore hold for the value n + 1. Doing so generally requires understanding how the hyp otheses for n and n + 1 are linked, and reducing the n + 1 case to the size n situation.^1 For example, in our present problem we assume that the summation of values from 1 to n is n(n 2 +1). We then inquire as to the sum of the values from 1 to n + 1. But this can b e written as (1 + 2 + : : : + n) + (n + 1). Our induction hypothesis tells us that we can substitute n(n+1) 2 for^ the^ rst^ term.^ The^ resulting^ expression^ is^
n(n+1) 2 +^ (n^ +^ 1),^ or^
n(n+1) 2 +^
2(n+1) 2 , which simpli es to (n+1)( 2 n+2). Because this matches our induction hyp othesis for n + 1, we are done. From this analysis, we can deduce that the numb er of iterations of the b o dy of the lo op in the bubble sort algorithm is (n 2 1) n. This is n
(^2) +n 2.^ As^ we^ will^ see^ when^ we^ discuss^ the (^1) Sometimes it is easier to assume the hyp othesis holds for integers smaller than n 1, and then prove it must therefore hold for n.
Unlike the bubble sort algorithm, the insertion sort algorithm places the lower p ortion of the array into sequence rst. Each new value is inserted into place, sliding elements over until the prop er lo cation for each new value is established.
the worst case must shift elements all the way to the b ottom. (This worst case o ccurs if the input is initially sorted backwards, and thus each value in turn is swapp ed until it reaches the zeroth element). We see, therefore, that in the worst case the numb er of iterations of the
series is (n 2 1) n, and thus the algorithm is O (n^2 ). (An optimist might argue that this worst case p erformance is rare, citing that in the b est case the inner lo op only executes one step, and therefore in this situation the insertion sort algorithm is O (n). Unfortunately, though the mathematics is more complicated than we can present here, it is p ossible to show that the average case b ehavior of insertion sort is still O (n^2 ).) More complicated uses of the while lo op o ccur when the variables involved are not simply tracing out an arithmetic progression. A classic example of a nontrivial while lo op o ccurs in the binary search algorithm. Here we assume that the input array is an already ordered collection of values. The task is to determine if a particular value o ccurs in the list and, if not, the p osition immediately ab ove to the lo cation where the element would b e placed.
// pre: elements in argument data are ordered smallest to largest // p ost: returns the index in data where testValue is found, // or index of next larger element if not in collection int low = 0; int high = data.length;
// rep eatedly reduce the area of search // until it is just one value
mid = (low + high) / 2; if (data[mid] < testValue) low = mid + 1; else high = mid;
return low;
The program works by rep eatedly dividing in half the range of values b eing searched. Because there were originally n values, we know the numb er of times the collection can b e sub divided is no larger than roughly log n (see nearby b ox on logarithms). This is sucient to tell us that the entire pro cedure is O (log n).
To the mathematician, a logarithm is generally envisioned as the inverse of the exp onential function, or p erhaps it is asso ciated with the integral calculus (that is, loge a =
1
1 x dx).^ To^ a^ computer^ scientist,^ the^ intuition^ concerning^ the^ log^ function should b e something very di erent.
The log (base n) of a p ositive value x is approximately equal to the numb er of times that x can b e divided by n.
Most often the log function will arise when quantities are rep eatedly split in half. This is why logarithms in computer science are, almost invariably, used with a base value two.
The log (base 2) of a p ositive value x is approximately equal to the numb er of times that x can b e divided in half.
The word \approximately" is used, b ecause the log function yields a fractional value, and the exact gure can b e as much as one larger than the integer ceiling of the log. But, as we have already noted, integer constants can b e safely ignored when discussing asymptotic b ounds.
When function or pro cedure calls o ccur, the running time of the call is taken to b e the running time of the asso ciated pro cedure. For example, supp ose we wished to print the values of all prime numb ers less than n. We could use an algorithm such as the following:
if (isPrime(i)) System.out.println("value " + i + " is prime"); else System.out.println("value " + i + " is not prime");
We know the execution time of the isPrime routine is O (
n). (In fact, we can make the even stronger statement that it is O (
i), but doing so results in a summation that is dicult to analyze, so we will b ound each call by the larger limit.) Because we are making roughly n calls, the total running time of the pro cedure is no greater than O (n
n).
Function Common name n! Factorial 2 n^ Exp onential nd^ , d > 3 Polynomial n^3 Cubic n^2 Quadratic n
n n log n
n Ro ot{n log n Logarithmic 1 Constant
In the following discussion we will motivate this rule in a variety of fashions. The rst is intended merely as an intuitive illustration. The reader has probably had the exp erience of sitting in a car during a rainstorm, and may have noted that small raindrops will stay xed on the angled front window, even if the car remains at rest. If more water collects in the drop, however, it eventually falls o. There is a certain limit in size b eyond which drops seemingly cannot remain xed on the window.