Docsity

Mark Allen Weiss - Data Structures and Algorithms-, Study Guides, Projects, Research of Electrical Engineering

Toggle sidebar
bg1
Data Structures and Algorithm Analysis in
C
by Mark Allen Weiss
PREFACE
CHAPTER 1: INTRODUCTION
CHAPTER 2: ALGORITHM ANALYSIS
CHAPTER 3: LISTS, STACKS, AND QUEUES
CHAPTER 4: TREES
CHAPTER 5: HASHING
CHAPTER 6: PRIORITY QUEUES (HEAPS)
CHAPTER 7: SORTING
CHAPTER 8: THE DISJOINT SET ADT
CHAPTER 9: GRAPH ALGORITHMS
CHAPTER 10: ALGORITHM DESIGN TECHNIQUES
CHAPTER 11: AMORTIZED ANALYSIS
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Mark Allen Weiss - Data Structures and Algorithms- and more Study Guides, Projects, Research Electrical Engineering in PDF only on Docsity!

Data Structures and Algorithm Analysis in

C

by Mark Allen Weiss

PREFACE

CHAPTER 1: INTRODUCTION

CHAPTER 2: ALGORITHM ANALYSIS

CHAPTER 3: LISTS, STACKS, AND QUEUES

CHAPTER 4: TREES

CHAPTER 5: HASHING

CHAPTER 6: PRIORITY QUEUES (HEAPS)

CHAPTER 7: SORTING

CHAPTER 8: THE DISJOINT SET ADT

CHAPTER 9: GRAPH ALGORITHMS

CHAPTER 10: ALGORITHM DESIGN TECHNIQUES

CHAPTER 11: AMORTIZED ANALYSIS

PREFACE

Purpose/Goals

This book describes data structures , methods of organizing large amounts of data, and

algorithm analysis, the estimation of the running time of algorithms. As computers

become faster and faster, the need for programs that can handle large amounts of input

becomes more acute. Paradoxically, this requires more careful attention to efficiency,

since inefficiencies in programs become most obvious when input sizes are large. By

analyzing an algorithm before it is actually coded, students can decide if a particular

solution will be feasible. For example, in this text students look at specific problems and

see how careful implementations can reduce the time constraint for large amounts of data

from 16 years to less than a second. Therefore, no algorithm or data structure is presented

without an explanation of its running time. In some cases, minute details that affect the

running time of the implementation are explored.

Once a solution method is determined, a program must still be written. As computers

have become more powerful, the problems they solve have become larger and more

complex, thus requiring development of more intricate programs to solve the problems.

The goal of this text is to teach students good programming and algorithm analysis skills

simultaneously so that they can develop such programs with the maximum amount of

efficiency.

This book is suitable for either an advanced data structures (CS7) course or a first-year

graduate course in algorithm analysis. Students should have some knowledge of

intermediate programming, including such topics as pointers and recursion, and some

background in discrete math.

Approach

I believe it is important for students to learn how to program for themselves, not how to

copy programs from a book. On the other hand, it is virtually impossible to discuss

realistic programming issues without including sample code. For this reason, the book

usually provides about half to three-quarters of an implementation, and the student is

encouraged to supply the rest.

The algorithms in this book are presented in ANSI C, which, despite some flaws, is

arguably the most popular systems programming language. The use of C instead of

Pascal allows the use of dynamically allocated arrays (see for instance rehashing in Ch.

5). It also produces simplified code in several places, usually because the and (&&)

operation is short-circuited.

Chapter 8 discusses the disjoint set algorithm with proof of the running time. This is a

short and specific chapter that can be skipped if Kruskal's algorithm is not discussed.

Chapter 9 covers graph algorithms. Algorithms on graphs are interesting not only because

they frequently occur in practice but also because their running time is so heavily

dependent on the proper use of data structures. Virtually all of the standard algorithms are

presented along with appropriate data structures, pseudocode, and analysis of running

time. To place these problems in a proper context, a short discussion on complexity

theory (including NP - completeness and undecidability) is provided.

Chapter 10 covers algorithm design by examining common problem-solving techniques.

This chapter is heavily fortified with examples. Pseudocode is used in these later chapters

so that the student's appreciation of an example algorithm is not obscured by

implementation details.

Chapter 11 deals with amortized analysis. Three data structures from Chapters 4 and 6

and the Fibonacci heap, introduced in this chapter, are analyzed.

Chapters 1-9 provide enough material for most one-semester data structures courses. If

time permits, then Chapter 10 can be covered. A graduate course on algorithm analysis

could cover Chapters 7-11. The advanced data structures analyzed in Chapter 11 can

easily be referred to in the earlier chapters. The discussion of NP - completeness in

Chapter 9 is far too brief to be used in such a course. Garey and Johnson's book on NP -

completeness can be used to augment this text.

Exercises

Exercises, provided at the end of each chapter, match the order in which material is

presented. The last exercises may address the chapter as a whole rather than a specific

section. Difficult exercises are marked with an asterisk, and more challenging exercises

have two asterisks.

A solutions manual containing solutions to almost all the exercises is available separately

from The Benjamin/Cummings Publishing Company.

References

References are placed at the end of each chapter. Generally the references either are

historical, representing the original source of the material, or they represent extensions

and improvements to the results given in the text. Some references represent solutions to

exercises.

Acknowledgments

I would like to thank the many people who helped me in the preparation of this and

previous versions of the book. The professionals at Benjamin/Cummings made my book

a considerably less harrowing experience than I had been led to expect. I'd like to thank

my previous editors, Alan Apt and John Thompson, as well as Carter Shanklin, who has

edited this version, and Carter's assistant, Vivian McDougal, for answering all my

questions and putting up with my delays. Gail Carrigan at Benjamin/Cummings and

Melissa G. Madsen and Laura Snyder at Publication Services did a wonderful job with

production. The C version was handled by Joe Heathward and his outstanding staff, who

were able to meet the production schedule despite the delays caused by Hurricane

Andrew.

I would like to thank the reviewers, who provided valuable comments, many of which

have been incorporated into the text. Alphabetically, they are Vicki Allan (Utah State

University), Henry Bauer (University of Wyoming), Alex Biliris (Boston University), Jan

Carroll (University of North Texas), Dan Hirschberg (University of California, Irvine),

Julia Hodges (Mississippi State University), Bill Kraynek (Florida International

University), Rayno D. Niemi (Rochester Institute of Technology), Robert O. Pettus

(University of South Carolina), Robert Probasco (University of Idaho), Charles Williams

(Georgia State University), and Chris Wilson (University of Oregon). I would

particularly like to thank Vicki Allan, who carefully read every draft and provided very

detailed suggestions for improvement.

At FIU, many people helped with this project. Xinwei Cui and John Tso provided me

with their class notes. I'd like to thank Bill Kraynek, Wes Mackey, Jai Navlakha, and Wei

Sun for using drafts in their courses, and the many students who suffered through the

sketchy early drafts. Maria Fiorenza, Eduardo Gonzalez, Ancin Peter, Tim Riley, Jefre

Riser, and Magaly Sotolongo reported several errors, and Mike Hall checked through an

early draft for programming errors. A special thanks goes to Yuzheng Ding, who

compiled and tested every program in the original book, including the conversion of

pseudocode to Pascal. I'd be remiss to forget Carlos Ibarra and Steve Luis, who kept the

printers and the computer system working and sent out tapes on a minute's notice.

This book is a product of a love for data structures and algorithms that can be obtained

only from top educators. I'd like to take the time to thank Bob Hopkins, E. C. Horvath,

and Rich Mendez, who taught me at Cooper Union, and Bob Sedgewick, Ken Steiglitz,

and Bob Tarjan from Princeton.

Finally, I'd like to thank all my friends who provided encouragement during the project.

In particular, I'd like to thank Michele Dorchak, Arvin Park, and Tim Snyder for listening

to my stories; Bill Kraynek, Alex Pelin, and Norman Pestaina for being civil next-door

(office) neighbors, even when I wasn't; Lynn and Toby Berk for shelter during Andrew,

and the HTMC for work relief.

Any mistakes in this book are, of course, my own. I would appreciate reports of any

errors you find; my e- mail address is [email protected].

CHAPTER 1: INTRODUCTION

In this chapter, we discuss the aims and goals of this text and briefly review programming

concepts and discrete mathematics. We will

See that how a program performs for reasonably large input is just as important as its

performance on moderate amounts of input.

Review good programming style.

Summarize the basic mathematical background needed for the rest of the book.

Briefly review recursion.

1.1. What's the Book About?

Suppose you have a group of n numbers and would like to determine the k th largest. This

is known as the selection problem. Most students who have had a programming course or

two would have no difficulty writing a program to solve this problem. There are quite a

few "obvious" solutions.

One way to solve this problem would be to read the n numbers into an array, sort the

array in decreasing order by some simple algorithm such as bubblesort, and then return

the element in position k.

A somewhat better algorithm might be to read the first k elements into an array and sort

them (in decreasing order). Next, each remaining element is read one by one. As a new

element arrives, it is ignored if it is smaller than the k th element in the array. Otherwise, it

is placed in its correct spot in the array, bumping one element out of the array. When the

algorithm ends, the element in the k th position is returned as the answer.

Both algorithms are simple to code, and you are encouraged to do so. The natural

questions, then, are which algorithm is better and, more importantly, is either algorithm

good enough? A simulation using a random file of 1 million elements and k = 500,

will show that neither algorithm finishes in a reasonable amount of time--each requires

several days of computer processing to terminate (albeit eventually with a correct answer).

An alternative method, discussed in Chapter 7, gives a solution in about a second. Thus,

although our proposed algorithms work, they cannot be considered good algorithms,

because they are entirely impractical for input sizes that a third algorithm can handle in a

reasonable amount of time.

A second problem is to solve a popular word puzzle. The input consists of a two-

dimensional array of letters and a list of words. The object is to find the words in the

puzzle. These words may be horizontal, vertical, or diagonal in any direction. As an

example, the puzzle shown in Figure 1.1 contains the words this, two, fat , and that. The

word this begins at row 1, column 1 (1,1) and extends to (1, 4); two goes from (1, 1) to (3,

1); fat goes from (4, 1) to (2, 3); and that goes from (4, 4) to (1, 1).

Again, there are at least two straightforward algorithms that solve the problem. For each

word in the word list, we check each ordered triple ( row, column, orientation ) for the

presence of the word. This amounts to lots of nested for loops but is basically

straightforward.

Alternatively, for each ordered quadruple ( row, column, orientation, number of

characters ) that doesn't run off an end of the puzzle, we can test whether the word

indicated is in the word list. Again, this amounts to lots of nested for loops. It is possible

to save some time if the maximum number of characters in any word is known.

It is relatively easy to code up either solution and solve many of the real- life puzzles

commonly published in magazines. These typically have 16 rows, 16 columns, and 40 or

so words. Suppose, however, we consider the variation where only the puzzle board is

given and the word list is essentially an English dictionary. Both of the solutions

proposed require considerable time to solve this problem and therefore are not acceptable.

However, it is possible, even with a large word list, to solve the problem in a matter of

seconds.

An important concept is that, in many problems, writing a working program is not good

enough. If the program is to be run on a large data set, then the running time becomes an

issue. Throughout this book we will see how to estimate the running time of a program

for large inputs and, more importantly, how to compare the running times of two

programs without actually coding them. We will see techniques for drastically improving

the speed of a program and for determining program bottlenecks. These techniques will

enable us to find the section of the code on which to concentrate our optimization efforts.

1 t h i s

2 w a t s

3 o a h g

4 f g d t

Figure 1.1 Sample word puzzle

1.2. Mathematics Review

This section lists some of the basic formulas you need to memorize or be able to derive

and reviews basic proof techniques.

The easiest formulas to remember are

and the companion,

In the latter formula, if 0 < a < 1, then

and as n tends to , the sum approaches 1/(1 - a ). These are the "geometric series" formulas.

We can derive the last formula for in the following manner. Let S be the sum. Then

S = 1 + a + a 2 + a3 + a 4 + a 5 +...

Then

aS = a + a 2 + a 3 + a 4 + a 5 +...

If we subtract these two equations (which is permissible only for a convergent series), virtually all the terms on the right side cancel,

leaving

S - aS = 1

which implies that

We can use this same technique to compute , a sum that occurs frequently. We write

and multiply by 2, obtaining

Subtracting these two equations yields

Thus, S = 2.

Another type of common series in analysis is the arithmetic series. Any such series can be evaluated from the basic formula.

For instance, to find the sum 2 + 5 + 8 +... + (3 k - 1), rewrite it as 3(1 + 2+ 3 +... + k ) - (1 + 1 + 1 +... + 1), which is clearly 3 k ( k +

1)/2 - k. Another way to remember this is to add the first and last terms (total 3 k + 1), the second and next to last terms (total 3 k + 1),

and so on. Since there are k /2 of these pairs, the total sum is k (3 k + 1)/2, which is the same answer as before.

The next two formulas pop up now and then but are fairly infrequent.

When k = - 1, the latter formula is not valid. We then need the following formula, which is used far more in computer science than in

other mathematical disciplines. The numbers, H N

, are known as the harmonic numbers, and the sum is known as a harmonic sum. The

error in the following approximation tends to y 0.57721566, which is known as Euler's constant.

These two formulas are just general algebraic manipulations.

PROOF:

The proof is by induction. For the basis, it is readily seen that the theorem is true when n = 1. For the inductive hypothesis, assume

that the theorem is true for 1 k n. We will establish that, under this assumption, the theorem is true for n + 1. We have

Applying the inductive hypothesis, we obtain

Thus,

proving the theorem.

Proof by Counterexample

The statement F k

k 2 is false. The easiest way to prove this is to compute F 11

Proof by Contradiction

Proof by contradiction proceeds by assuming that the theorem is false and showing that this assumption implies that some known

property is false, and hence the original assumption was erroneous. A classic example is the proof that there is an infinite number of

primes. To prove this, we assume that the theorem is false, so that there is some largest prime p k

. Let p 1

, p 2

,... , p k

be all the primes

in order and consider

N = p 1

p 2

p 3

... p k

  • 1

Clearly, N is larger than p k

, so by assumption N is not prime. However, none of p 1

, p 2

,... , p k

divide N exactly, because there will

always be a remainder of 1. This is a contradiction, because every number is either prime or a product of primes. Hence, the original

assumption, that p k

is the largest prime, is false, which implies that the theorem is true.

int

f( int x )

{

/1/ if ( x = 0 )

/2/ return 0;

else

/3/ return( 2f(x-1) + xx );

}

Figure 1.2 A recursive function

1.3. A Brief Introduction to Recursion

Most mathematical functions that we are familiar with are described by a simple formula. For instance, we can convert temperatures

from Fahrenheit to Celsius by applying the formula

C = 5( F - 32)/

Given this formula, it is trivial to write a C function; with declarations and braces removed, the one-line formula translates to one line

of C.

Mathematical functions are sometimes defined in a less standard form. As an example, we can define a function f , valid on

nonnegative integers, that satisfies f (0) = 0 and f ( x ) = 2 f ( x - 1) + x 2. From this definition we see that f (1) = 1, f (2) = 6, f (3) = 21, and f (4)

= 58. A function that is defined in terms of itself is called recursive. C allows functions to be recursive.* It is important to remember

that what C provides is merely an attempt to follow the recursive spirit. Not all mathematically recursive functions are efficiently (or

correctly) implemented by C's simulation of recursion. The idea is that the recursive function f ought to be expressible in only a few

lines, just like a non-recursive function. Figure 1.2 shows the recursive implementation of f.

*Using recursion for numerical calculations is usually a bad idea. We have done so to illustrate the basic points.

Lines 1 and 2 handle what is known as the base case , that is, the value for which the function is directly known without resorting to

recursion. Just as declaring f ( x) = 2 f ( x - 1) + x 2 is meaningless, mathematically, without including the fact that f (0) = 0, the recursive

C function doesn't make sense without a base case. Line 3 makes the recursive call.

There are several important and possibly confusing points about recursion. A common question is: Isn't this just circular logic? The

answer is that although we are defining a function in terms of itself, we are not defining a particular instance of the function in terms

of itself. In other words, evaluating f (5) by computing f (5) would be circular. Evaluating f (5) by computing f (4) is not circular--unless,

of course f (4) is evaluated by eventually computing f (5). The two most important issues are probably the how and why questions. In

Chapter 3, the how and why issues are formally resolved. We will give an incomplete description here.

It turns out that recursive calls are handled no differently from any others. If f is called with the value of 4, then line 3 requires the

computation of 2

f (3) + 4

  1. Thus, a call is made to compute f (3). This requires the computation of 2

f (2) + 3

  1. Therefore,

another call is made to compute f (2). This means that 2

f (1) + 2

2 must be evaluated. To do so, f (1) is computed as 2

f (0) + 1

Suppose we have a positive integer, n , that we wish to print out. Our routine will have the heading print_out ( n ). Assume that the only

I/O routines available will take a single-digit number and output it to the terminal. We will call this routine print_digit ; for example,

print_digit (4) will output a 4 to the terminal.

Recursion provides a very clean solution to this problem. To print out 76234, we need to first print out 7623 and then print out 4. The

second step is easily accomplished with the statement print_digit ( n %10), but the first doesn't seem any simpler than the original

problem. Indeed it is virtually the same problem, so we can solve it recursively with the statement print_out ( n /10).

This tells us how to solve the general problem, but we still need to make sure that the program doesn't loop indefinitely. Since we

haven't defined a base case yet, it is clear that we still have something to do. Our base case will be print_digit ( n ) if 0 n < 10. Now

print_out ( n ) is defined for every positive number from 0 to 9, and larger numbers are defined in terms of a smaller positive number.

Thus, there is no cycle. The entire procedure* is shown Figure 1.4.

*The term procedure refers to a function that returns void.

We have made no effort to do this efficiently. We could have avoided using the mod routine (which is very expensive) because n %

= n - (^) n /

Recursion and Induction

Let us prove (somewhat) rigorously that the recursive number-printing program works. To do so, we'll use a proof by induction.

THEOREM 1.

The recursive number-printing algorithm is correct for n 0.

PROOF:

First, if n has one digit, then the program is trivially correct, since it merely makes a call to print_digit. Assume then that print_out

works for all numbers of k or fewer digits. A number of k + 1 digits is expressed by its first k digits followed by its least significant

digit. But the number formed by the first k digits is exactly (^) n /10 , which, by the indicated hypothesis is correctly printed, and the last

digit is n mod10, so the program prints out any ( k + 1)-digit number correctly. Thus, by induction, all numbers are correctly printed.

void

print_out( unsigned int n ) /* print nonnegative n */

{

if( n<10 )

print_digit( n );

else

{

print_out( n/10 );

print_digit( n%10 );

}

}

Figure 1.4 Recursive routine to print an integer

This proof probably seems a little strange in that it is virtually identical to the algorithm description. It illustrates that in designing a

recursive program, all smaller instances of the same problem (which are on the path to a base case) may be assumed to work correctly.

The recursive program needs only to combine solutions to smaller problems, which are "magically" obtained by recursion, into a

solution for the current problem. The mathematical justification for this is proof by induction. This gives the third rule of recursion:

  1. Design rule. Assume that all the recursive calls work.

This rule is important because it means that when designing recursive programs, you generally don't need to know the details of the

bookkeeping arrangements, and you don't have to try to trace through the myriad of recursive calls. Frequently, it is extremely difficult

to track down the actual sequence of recursive calls. Of course, in many cases this is an indication of a good use of recursion, since the

computer is being allowed to work out the complicated details.

The main problem with recursion is the hidden bookkeeping costs. Although these costs are almost always justifiable, because

recursive programs not only simplify the algorithm design but also tend to give cleaner code, recursion should never be used as a

substitute for a simple for loop. We'll discuss the overhead involved in recursion in more detail in Section 3.3.

When writing recursive routines, it is crucial to keep in mind the four basic rules of recursion:

  1. Base cases. You must always have some base cases, which can be solved without recursion.
  2. Making progress. For the cases that are to be solved recursively, the recursive call must always be to a case that makes progress

toward a base case.

  1. Design rule. Assume that all the recursive calls work.
  2. Compound interest rule. Never duplicate work by solving the same instance of a problem in separate recursive calls.

The fourth rule, which will be justified (along with its nickname) in later sections, is the reason that it is generally a bad idea to use

recursion to evaluate simple mathematical functions, such as the Fibonacci numbers. As long as you keep these rules in mind,

recursive programming should be straightforward.

Summary

This chapter sets the stage for the rest of the book. The time taken by an algorithm confronted with large amounts of input will be an

important criterion for deciding if it is a good algorithm. (Of course, correctness is most important.) Speed is relative. What is fast for

one problem on one machine might be slow for another problem or a different machine. We will begin to address these issues in the

next chapter and will use the mathematics discussed here to establish a formal model.

Exercises

1.1 Write a program to solve the selection problem. Let k = n /2. Draw a table showing the running time of your program for various

values of n.

1.2 Write a program to solve the word puzzle problem.

1.10 Prove the following formulas:

References

There are many good textbooks covering the mathematics reviewed in this chapter. A small subset is [1], [2], [3], [11], [13], and [14].

Reference [11] is specifically geared toward the analysis of algorithms. It is the first volume of a three-volume series that will be cited

throughout this text. More advanced material is covered in [6].

Throughout this book we will assume a knowledge of C [10]. Occasionally, we add a feature where necessary for clarity. We also

assume familiarity with pointers and recursion (the recursion summary in this chapter is meant to be a quick review). We will attempt

to provide hints on their use where appropriate throughout the textbook. Readers not familiar with these should consult [4], [8], [12],

or any good intermediate programming textbook.

General programming style is discussed in several books. Some of the classics are [5], [7], and [9].

  1. M. O. Albertson and J. P. Hutchinson, Discrete Mathematics with Algorithms , John Wiley & Sons, New York, 1988.
  2. Z. Bavel, Math Companion for Computer Science , Reston Publishing Company, Reston, Va., 1982.
  3. R. A. Brualdi, Introductory Combinatorics , North-Holland, New York, 1977.
  4. W. H. Burge, Recursive Programming Techniques , Addison-Wesley, Reading, Mass., 1975.
  5. E. W. Dijkstra, A Discipline of Programming , Prentice Hall, Englewood Cliffs, N.J., 1976.
  6. R. L. Graham, D. E. Knuth, and O. Patashnik, Concrete Mathematics , Addison-Wesley, Reading, Mass., 1989.
  7. D. Gries, The Science of Programming , Springer-Verlag, New York, 1981.
  8. P. Helman and R. Veroff, Walls and Mirrors: Intermediate Problem Solving and Data Structures , 2d ed., Benjamin Cummings

Publishing, Menlo Park, Calif., 1988.

  1. B. W. Kernighan and P. J. Plauger, The Elements of Programming Style , 2d ed., McGraw- Hill, New York, 1978.
  2. B. W. Kernighan and D. M. Ritchie, The C Programming Language , 2d ed., Prentice Hall, Englewood Cliffs, N.J., 1988.
  3. D. E. Knuth, The Art of Computer Programming, Vol. 1: Fundamental Algorithms , 2d ed., Addison-Wesley, Reading, Mass., 1973.
  4. E. Roberts, Thinking Recursively , John Wiley & Sons, New York, 1986.
  1. F. S. Roberts, Applied Combinatorics , Prentice Hall, Englewood Cliffs, N.J., 1984.
  2. A. Tucker, Applied Combinatorics , 2d ed., John Wiley & Sons, New York, 1984.

Go to Chapter 2 Return to Table of Contents