Docsity

Algorithmic Analysis: Understanding Big-O Notation & Execution Time in CS, Papers of Computer Science

Toggle sidebar
bg1
Chapter 1
Execution Time Measurement
In comparing two dierent implementations of the same ADT, an important question to
address is their relative execution times. It might appear, at rst, that describing the
execution time of a computer algorithm should be easy. One merely runs the algorithm
with a stopwatch in hand (or anynumberoftechnological variations of a similar theme) and
records the results. And indeed, such a value, called a
benchmark
, is occasionally useful.
We will examine benchmarks later in this chapter.
Most of the time, however, a benchmark is not a good characterization of a computer
algorithm. A benchmark only describes the actual p erformance of a program on a specic
machine on a given day. Dierent processors can have dramatically dierent performances
(computer manufacturers go to great lengths to remind users of this fact in hopes of entic-
ing them to purchase faster and more costly machines). Even working on a single machine,
there may be a selection of many alternative compilers for the same programming language.
These compilers will produce slightly dierent machine code instructions for the same source
language, and thus havevarying execution times. Finally, execution timings for multipro-
cessing computers (computers that can perform many tasks simultaneously) will be altered
by the other tasks being performed at the same time.
In this chapter we introduce the concept of
algorithmic analysis
(or
analysis of algo-
rithms
), a technique used to characterize the execution behavior of algorithms in a manner
independent of a particular platform, compiler, or language. Many of the data structures
described in this book provide similar functionality, but dier in their execution times for
various operations. Thus, selecting the appropriate type 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.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b

Partial preview of the text

Download Algorithmic Analysis: Understanding Big-O Notation & Execution Time in CS and more Papers Computer Science in PDF only on Docsity!

Chapter 1

Execution Time Measurement

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.

2 CHAPTER 1. EXECUTION TIME MEASUREMENT

1.1 Algorithmic Analysis and Big-Oh Notation

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

the machine b eing used). In total, the running time of the pro cess is therefore c  n for some

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

using only log n comparisons. Thus the real running time is some function d  log n for some

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

(smaller than or equal to) the quantity c  g (n). Although this formal de nition may b e

of critical imp ortance to theoreticians, an intuitive feeling for algorithmic execution is of

4 CHAPTER 1. EXECUTION TIME MEASUREMENT

return Color.red; else return Color.black;

g

g

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.

1.2.2 Simple Lo ops

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:

public class CardDeck f

CardDeck () f

int topCard = 0;

for (int i = 1; i <= 13; i++) f

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);

g

g

private Card [ ] cards = new Card[52]; ...

g

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:

public double minimum (double [ ] values) f

// pre: values has at least one element // p ost: returns smallest value in collection int n = values.length; double minValue = values[0];

for (int i = 1; i < n; i++) f

1.2. EXECUTION TIME OF PROGRAMMING CONSTRUCTS 5

The Array in Java

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:

public class AnApplication f

public static void main (String [ ] args) f

...

g

g

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.

1.2. EXECUTION TIME OF PROGRAMMING CONSTRUCTS 7
1.2.3 Nested Lo ops

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.

void matprod (double [ ][ ] a, double [ ] [ ] b, double [ ] [ ] c) f

int n = a.length;

for (int i = 0; i < n; i++) f

for (int j = 0; j < n; j++) f

c[i][j] = 0.0;

for (int k = 0; k < n; k++) f

c[i][j] += a[i][k]  b[k][j];

g

g

g

g

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.

void bubbleSort (double [ ] v) f

int n = v.length; // nd the largest remaining value // and place into v[i]

for (int i = n - 1; i > 0; i--) f

// move large values to the top

for (int j = 0; j < i; j++) f

if (v[j] > v[j+1]) f // if out of order

double temp = v[j]; // then swap v[j] = v[j + 1]; v[j + 1] = temp;

g

8 CHAPTER 1. EXECUTION TIME MEASUREMENT

g

g

g

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

outermost lo op, the inner lo op will execute n 1 times. On the second iteration of the

outermost lo op, the inner lo op will execute n 2 times, and so on until on the nal iteration

the inner lo op executes 1 time. The numb er of iterations is therefore the sum of (n 1) +

(n 2) + : : : + 1.

Mathematical Induction

In order to determine the size of the sum (n 1) + (n 2) + : : : + 1, we use a p owerful technique,

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.

10 CHAPTER 1. EXECUTION TIME MEASUREMENT

g

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 outer lo op clearly executes n 1 times. The inner lo op may terminate early, but in

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

inner lo op follows the pattern 1 + 2 + 3 + 4 + : : : + (n 1). As we have seen, the sum of this

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.

int binarySearch (double [ ] data, double testValue) f

// 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

while (low < high) f

mid = (low + high) / 2; if (data[mid] < testValue) low = mid + 1; else high = mid;

g

return low;

g

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).

1.2. EXECUTION TIME OF PROGRAMMING CONSTRUCTS 11

Logarithms

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 =

R 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.

1.2.5 Function Calls

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:

public void printPrimes (int n) f

for (int i = 2; i <= n; i++) f

if (isPrime(i)) System.out.println("value " + i + " is prime"); else System.out.println("value " + i + " is not prime");

g

g

We know the execution time of the isPrime routine is O (

p

n). (In fact, we can make the even stronger statement that it is O (

p

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

p

n).

1.3. SUMMING ALGORITHMIC EXECUTION TIMES 13

Function Common name n! Factorial 2 n^ Exp onential nd^ , d > 3 Polynomial n^3 Cubic n^2 Quadratic n

p

n n log n

pn^ Linear

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.

The force pulling the drop down is gravity, while the force p ermitting the drop to remain on the windscreen is friction, or the surface tension b etween the drop and the glass. We can idealize the situation slightly and consider the drop to b e a p erfect hemisphere. If r represents the radius of the drop, the surface area b etween the drop and the plane is  r 2. Gravity, on the other hand, op erates on the entire volume of the drop, which is prop ortional

to r 3. Thus, the force of gravity can b e describ ed by c  r 3 , for some unknown constant c,

and the force of surface tension is similarly describ ed by d  r 2 , making use of some unknown

constant d. The observed phenomenon is that small drops will remain on the surface. This is the situation when the force of the surface tension is greater than that of gravity. As the drop b ecomes larger, its radius increases. Eventually, no matter what the constants may b e, a cubic (r 3 ) function will always b ecome larger than a quadratic (r 2 ) function. Thus, we would predict that large drops must always fall o the surface, b ecause gravity prevails over surface tension. This, of course, matches what we observe.

14 CHAPTER 1. EXECUTION TIME MEASUREMENT

Linear Quadratic Cubic Ro ot-n Log n Constant

Figure 1.1: Characteristic curves for various functions

We can see this b ehavior in a graphical fashion by noting the curves given by various functions. All functions p ossess a certain characteristic curve. Figure ?? illustrates these curves for various functions. An n^3 function will always grow faster than, and thus always eventually surpass an n^2 function, regardless of the constant values involved either as co- ecient on the function or as an additive amount. This is shown in Figure ??, where the function n

2

4 is^ compared^ against^ the^ amount^200 +^ n^ ^ log^ n.^ Although^ the^ latter^ is^ initially

much larger, the n^2 function must always eventually dominate. When two functions of di erent orders of magnitude are combined, the larger function will dominate the smaller one, so that the characteristic shap e of the result matches the larger, and not the smaller. This is shown in Figure ??, which compares the functions n, n^2 , and the combination n^2 + n. Another way to understand this is to consider a few actual values for the various func- tions. Assume, for example, that we can p erform one op eration every microsecond (that is, 106 op erations p er second), and we have some task that requires an input of size 105. The gures in Table ?? illustrate how long it would take to p erform this task, assuming various di erent running times. The multiplication of the dominant function by a constant will, of course, change the running time, but only by a constant factor. Consider a task that requires n^2 + n log n steps. The n^2 part will mean the task will require several hours to complete, while the n log n comp onent will add an insigni cant few additional seconds to the execution time. Taking all of these arguments into consideration, it seems intuitive that

16 CHAPTER 1. EXECUTION TIME MEASUREMENT

function Running time 2 n^ More than a century n^3 31 : 7 years n^2 2 : 8 hours n

p

n 31 : 6 seconds n log n 1 : 2 seconds

p^ n^0 :^1 seconds

n 3 : 2  10 ^4 seconds

log n 1 : 2  10 ^5 seconds

Table 1.1: Execution times for a task using n = 105 input values, assuming 106 op erations can b e p erformed p er second

when we add algorithmic execution times, it is safe to ignore all terms except the dominant function. (For those who have a natural dislike for intuitive arguments, some of the exercises at the end of the chapter will place this assertion on a more formal grounding.)

1.4 The Imp ortance of Fast Algorithms

The following story will help illustrate b oth the imp ortance of nding fast algorithms and data structures, and that the most obvious approach to solving a problem may not neces- sarily b e the b est. Several years ago a student working in genetic research was faced with a task involved in the analysis of DNA sequences. The problem could b e reduced to a relatively simple form. The DNA is represented as a array of n integer values, where n is very large (on the order of tens of thousands). The problem was to discover whether any pattern of length m, where m was a xed and small constant (say ve or ten) is ever rep eated in the array of values.

1 n

m m

t c^ g^ a^ g

z }| {

t c^ g^ a^ g

z }| {

The programmer dutifully sat down and wrote a simple and straightforward program, something like the following: for (int i = 0; i < (n-m); i++)

for (int j = i+1; j < (n-m); j++) f

boolean found = true;

for (k = 0; k < m; k++) f

if (x[i+k] != x[j+k])

1.4. THE IMPORTANCE OF FAST ALGORITHMS 17

found = false;

g

if (found) f

...

g

g

The student was somewhat disapp ointed when trial runs indicated his program would need several days to complete. He discussed his problem with a second student, who sug- gested a di erent approach. Rather than working with a array of n elements, the second student reorganized the data into a matrix with roughly n rows and m columns:

x 1 x 2 ... xm x 2 x 3 ... xm+ ... ... xnm ... ... xn 1 xn(m1) ... xn 1 xn

The second student then wrote a program to sort this matrix by rows. If any pattern was rep eated, then two adjacent rows in the sorted matrix would have identical values. It was a trivial matter to check for this condition. As we will see in later chapters, sorting can b e made an O (n log n) time op eration. Sort-

ing a matrix can b e p erformed by an algorithm that is O (m  n log n), whereas the original

program was O (m  n^2 ). This was a considerable improvement, reducing the estimated

execution time from several days to slightly less than one day. At this p oint a third student entered the ro om, and said that she had a technique that could reduce the execution time even further. The approach describ ed by the third student was to take each section of m values, and reduce it to a single integer value, for example by adding the elements. This is a technique called hashing, and we will examine it in detail in Chapter ??. The student then constructed another array of roughly n elements. For each hashed entry, she placed a string representing the run of m characters at the lo cation given by the hash value taken mo d the size of the array:

@ @R \gtatg"

@ @R \tagac"

@ @R \ctgta"

If two elements were equal, they would have the same hash value. It was therefore a simple matter to examine the array prior to placing each value to see if the same value had already b een seen. Since all this could b e p erformed in one pass through the original data

array, it was O (m  n), which was even faster than the O (m  n log n) solution. Using this

technique, the student was able to reduce the data analysis phase of his work from several days to well under one day of execution time.

1.5. BENCHMARKING ACTUAL EXECUTION TIMES 19

The Java Big Bang

In Chapter ?? we noted that an ob ject-oriented program can b e envisioned as a universe of interacting ob jects. It is helpful to keep this image in mind when considering how Java program typically start execution. The pro cedure main must b e declared b oth public and static. The latter characteristic is necessary since only static metho ds can b e executed prior to the creation of any instances of a class. Often, as in Figure ??, the most imp ortant action the main program must p er- form is to create the rst ob ject that will o ccupy the ob ject-oriented universe. (Sometimes it is the only action). The constructor for this class will then pro ceed to create other ob jects, until all the necessary elements in the universe are formed. In this program we create a GraphMaker and instances of two di erent sub classes of TaskTimer. The GraphMaker will, in turn, create instances of Rep orter. Finally, the program is set in motion, and the output is displayed.

overwritten by the user to sp ecify the task to b e p erformed. The metho d run rep eatedly executes the given tasks, computing the execution time, and recording the execution times using the rep orter.

The co de in Figure ?? shows how we can create a sub class of TaskTimer to compute the running time of the bubble sort algorithm describ ed earlier in Section ??. This gure also shows how to create the main application that combines the GraphMaker and the TaskTimers. Running the BubbleExp eriment program pro duces output such as that shown in Figure ??. Note that although the execution timings for the two algorithms show clear trends, they are not precise. This is characteristic of actual execution timings. Features such as memory management, the need for the hardware to resp ond to other pro cesses, and other uncertain factors can combine to make small (or sometimes, very large) deviations in execution timings. Thus no single timing should ever b e taken to b e representative of the p erformance of an algorithm. Instead, a numb er of rep eated timings should b e obtained, so as to smo oth out any transient e ects.

We can see from Figure ?? that although Bubble Sort and Insertion Sort have the same asymptotic execution time (they are b oth O (n^2 )), in practice insertion sort tends to b e slightly faster.

20 CHAPTER 1. EXECUTION TIME MEASUREMENT

class BubbleTime extends TaskTimer f

BubbleTime (Reporter out) f super(out); g

public void initialize (int n) f

data = new double[n]; // create new array for (int i = 0; i < n; i++) // ll with random values

data[i] = n  Math.random();

g

public void doTask (int n) f bubbleSort(data); g

private double [ ] data;

private void bubbleSort (double [ ] v) f ... g

g

public class BubbleExperiment extends Frame f

public static void main (String [ ] args) f

BubbleExperiment world = new BubbleExperiment(); world.show(); world.run();

g

public BubbleExperiment () f

setTitle("Bubble Sort and Insertion Sort Comparison"); setSize(500, 300); add("Center", graph);

g

private GraphMaker graph = new GraphMaker(5000, 3000);

public void run() f

BubbleTime bTimer = new BubbleTime(graph.getReporter("Bubble")); bTimer.run(0, 5000, 100); InsertionTime iTimer = new InsertionTime(graph.getReporter("Insertion")); iTimer.run(0, 5000, 100);

g

g

Figure 1.5: The class BubbleExp eriment