PDF | On Jan 1, , Ellis Horowitz and others published Fundamentals of Data Structure in C++. DATA REPRESENTATIONS FOR STRINGS . PATTERN MATCHING IN STRINGS. Fundamentals of Data Structures in C Horowitz PDF Fundamentals Of Data Structures In C Author: Ellis Horowitz, Anderson-Freed, Sahni other link other link .

Author: | PATRIA FRYMARK |

Language: | English, Spanish, Dutch |

Country: | Guyana |

Genre: | Politics & Laws |

Pages: | 196 |

Published (Last): | 03.06.2016 |

ISBN: | 786-1-53586-300-2 |

ePub File Size: | 19.32 MB |

PDF File Size: | 8.88 MB |

Distribution: | Free* [*Regsitration Required] |

Downloads: | 36245 |

Uploaded by: | LEOTA |

Fundamentals of Data Structures - Ellis Horowitz, Sartaj soundofheaven.info - Ebook download as PDF File .pdf), Text File .txt) or read book online. data structure. It is not a diet book but Healthy Weight Loss – Without Dieting. Following the In this effective Healthiest Way of E Fundamentals of Data Structures – Ellis. Fundamentals: Table of Contents soundofheaven.info Fundamentals of Data Structures by Ellis Horowitz and Sartaj Sahni PREFACE CHAPTER 1.

Vintage CIA sweatshirt with patches variable. This implies a mastery of two techniques: For a name beginning with, say, S, we would avoid having to look at names beginning with other letters. For example F 2. Consequently, on each iteration the value of only one of p or q increases by 2.

The point is that algorithms can be devised for many common activities. Have you studied the flowchart? Then you probably have realized that it isn't an algorithm at all! Which properties does it lack? Returning to our earlier definition of computer science, we find it extremely unsatisfying as it gives us no insight as to why the computer is revolutionizing our society nor why it has made us re-examine certain basic assumptions about our own role in the universe.

While this may be an unrealistic demand on a definition even from a technical point of view it is unsatisfying. The definition places great emphasis on the concept of algorithm, but never mentions the word "data". If a computer is merely a means to an end, then the means may be an algorithm but the end is the transformation of data. That is why we often hear a computer referred to as a data processing machine. Raw data is input and algorithms are used to transform it into refined data.

So, instead of saying that computer science is the study of algorithms, alternatively, we might say that computer science is the study of data: Figure 1. Flowchart for obtaining a Coca-Cola There is an intimate connection between the structuring of data, and the synthesis of algorithms.

In fact, a data structure and an algorithm should be thought of as a unit, neither one making sense without the other. For instance, suppose we have a list of n pairs of names and phone numbers a1,b1 a2,b2 , This task is called searching. Just how we would write such an algorithm critically depends upon how the names and phone numbers are stored or structured. One algorithm might just forge ahead and examine names, a1,a2,a3, This might be fine in Oshkosh, but in Los Angeles, with hundreds of thousands of names, it would not be practical.

If, however, we knew that the data was structured so that the names were in alphabetical order, then we could do much better.

We could make up a second list which told us for each letter in the alphabet, where the first name with that letter appeared. For a name beginning with, say, S, we would avoid having to look at names beginning with other letters. So because of this new structure, a very different algorithm is possible. Other ideas for algorithms become possible when we realize that we can organize the data as we wish.

We will discuss many more searching strategies in Chapters 7 and 9. Therefore, computer science can be defined as the study of data, its representation and transformation by a digital computer. The goal of this book is to explore many different kinds of data objects. For each object, we consider the class of operations to be performed and then the way to represent this object so that these operations may be efficiently carried out.

This implies a mastery of two techniques: The pedagogical style we have chosen is to consider problems which have arisen often in computer applications.

For each problem we will specify the data object or objects and what is to be accomplished. After we have decided upon a representation of the objects, we will give a complete algorithm and analyze its computing time. After reading through several of these examples you should be confident enough to try one on your own.

There are several terms we need to define carefully before we proceed. These include data structure, data object, data type and data representation. These four terms have no standard meaning in computer science circles, and they are often used interchangeably. A data type is a term which refers to the kinds of data that variables may "hold" in a programming language. With every programming language there is a set of built-in data types.

This means that the language allows variables to name data of that type and. Some data types are easy to provide because they are already built into the computer's machine language instruction set. Integer and real arithmetic are examples of this. Other data types require considerably more effort to implement. In some languages, there are features which allow one to construct combinations of the built-in types.

However, it is not necessary to have such a mechanism. All of the data structures we will see here can be reasonably built within a conventional programming language.

Data object is a term referring to a set of elements, say D. Thus, D may be finite or infinite and if D is very large we may need to devise special ways of representing its elements in our computer. The notion of a data structure as distinguished from a data object is that we want to describe not only the set of objects, but the way they are related. Saying this another way, we want to describe the set of operations which may legally be applied to elements of the data object.

This implies that we must specify the set of operations and show how they work. To be more precise lets examine a modest example.

The following notation can be used: SUCC stands for successor. The rules on line 8 tell us exactly how the addition operation works. For example if we wanted to add two and three we would get the following sequence of expressions: In practice we use bit strings which is a data structure that is usually provided on our computers. But however the ADD operation is implemented, it must obey these rules. Hopefully, this motivates the following definition.

A data structure is a set of domains , a designated domain , a set of functions and a end. It is called abstract precisely because the axioms do not imply a form of representation.

Our goal here is to write the axioms in a representation independent way. Thus we say that integers are represented by bit strings. We might begin by considering using some existing language. But at the first stage a data structure should be designed so that we know what it does. Another way of viewing the implementation of a data structure is that it is the process of refining an abstract data type until all of the operations are expressible in terms of directly executable functions.

An implementation of a data structure d is a mapping from d to a set of other data structures e. Though some of these are more preferable than others. This division of tasks. This mapping specifies how every object of d is to be represented by the objects of e. In current parlance the triple is referred to as an abstract data type. Furthermore it is not really necessary to write programs in a language for which a compiler exists. We would rather not have any individual rule us out simply because he did not know or.

The triple denotes the data structure d and it will usually be abbreviated by writing In the previous example The set of axioms describes the semantics of the operations. Thus we would have to make pretense to build up a capability which already exists. First of all. The form in which we choose to write the axioms is important. Instead we choose to use a language which is tailored to describing the algorithms we want to write.

The way to assign values is by the assignment statement variable expression. Several cute ideas have been suggested. In addition to the assignment statement. Several such statements can be combined on a single line if they are separated by a semi-colon. Expressions can be either arithmetic.. In order to produce these values.

In the boolean case there can be only one of two values.. Most importantly. The meaning of this statement is given by the flow charts: Though this is very interesting from a theoretical viewpoint. S is as S1 before and the meaning is given by It is well known that all "proper" programs can be written using only the assignment. To accomplish iteration..

If S1 or S2 contains more than one statement. Brackets must be used to show how each else corresponds to one if. So we will provide other statements such as a second iteration statement.

On the contrary. This result was obtained by Bohm and Jacopini. One of them is while cond do S end where cond is as before.

Another iteration statement is loop S forever which has the meaning As it stands. One way of exiting such a loop is by using a go to label statement which transfers control to "label. A more restricted form of the go to is the command exit which will cause a transfer of control to the first statement after the innermost loop which contains it.

This looping statement may be a while.. The semantics is easily described by the file: We can write the meaning of this statement in SPARKS as vble fin incr start finish increment 0 do start to finish by increment do while vble.. It has the form where the Si. A variable or a constant is a simple form of an expression. A procedure may be invoked by using a call statement call NAME parameter list Procedures may call themselves.

The else clause is optional. The execution of an end at the end of procedure implies a return. Though recursion often carries with it a severe penalty at execution time. This may be somewhat restrictive in practice. All procedures are treated as external.

The expr may be omitted in which case a return is made to the calling procedure. Parameters which are constants or values of expressions are stored into internally generated words whose addresses are then passed to the procedure. Many such programs are easily translatable so that the recursion is removed and efficiency achieved. The association of actual to formal parameters will be handled using the call by reference rule. This penalty will not deter us from using recursion.

This means that at run time the address of each parameter is passed to the called procedure. This is a goal which should be aimed at by everyone who writes programs. These are often useful features and when available they should be used. We avoid the problem of defining a "format" statement as we will need only the simplest form of input and output.. See the book The Elements of Programming Style by Kernighan and Plauger for more examples of good rules of programming.

The command stop halts execution of the currently executing procedure. Comments may appear anywhere on a line enclosed by double slashes..

An n-dimensional array A with lower and upper bounds li.. We have avoided introducing the record or structure concept. The SPARKS language is rich enough so that one can create a good looking program by applying some simple rules of style. Avoid sentences like ''i is increased by one. It is often at this point that one realizes that a much better program could have been built. But to improve requires that you apply some discipline to the process of creating programs.

Assume that these operations already exist in the form of procedures and write an algorithm which solves the problem according to the requirements. Designing an algorithm is a task which can be done independently of the programming language you eventually plan to use. One of the criteria of a good design is file: Use a notation which is natural to the way you wish to describe the order of processing.

If you have been careful about keeping track of your previous work it may not be too difficult to make changes. You should consider alternatives. In fact. Can you think of another algorithm? If so. Make sure you understand the information you are given the input and what results you are to produce the output. You are now ready to proceed to the design phase. This method uses the philosophy: It may already be possible to tell if one will be more desirable than the other.

To understand this process better.

The order in which you do this may be crucial. Modern pedagogy suggests that all processing which is independent of the data representation be written out first. Perhaps you should have chosen the second design alternative or perhaps you have spoken to a friend who has done it better.

By postponing the choice of how the data is stored we can try to isolate what operations depend upon the choice of data representation.

For each object there will be some basic operations to perform on it such as print the maze. Try to write down a rigorous description of the input and output which covers all cases. You must now choose representations for your data objects a maze as a two dimensional array of zeros and ones.

Finally you produce a complete version of your first program. If you can't distinguish between the two. You may have several data objects such as a maze. We hope your productivity will be greater. This happens to industrial programmers as well. The larger the software. The proof can't be completed until these are changed. The previous discussion applies to the construction of a single procedure as well as to the writing of a large software system.

Verification consists of three distinct aspects: Before executing your program you should attempt to prove it is correct.. Unwarrented optimism is a familiar disease in computing. This shifts our emphasis away from the management and integration of the file: One thing you have forgotten to do is to document. Different situations call for different decisions. One such tool instruments your source code and then tells you for every data set: As a minimal requirement.

Proofs about programs are really no different from any other kinds of proofs. B and C. If the program fails to respond correctly then debugging is needed to determine what went wrong and how to correct it. Testing is the art of creating sample data upon which to run your program. For each subsequent compiler their estimates became closer to the truth. It is usually hard to decide whether to sacrifice this first attempt and begin again or just continue to get the first version working.

But why bother to document until the program is entirely finished and correct? Because for each procedure you made some assumptions about its input and output. The graph in figure 1. In fact you may save as much debugging time later on by doing a new version now. If you note them down with the code. Each of these is an art in itself. If you do decide to scrap your work and begin again. For each compiler there is the time they estimated it would take them and the time it actually took.

Finally there may be tools available at your computing center to aid in the testing process. Let us concentrate for a while on the question of developing a single procedure which solves a specific task. Many times during the proving process errors are discovered in the code.

This is a phenomenon which has been observed in practice. If you have written more than a few procedures. This is another use of program proving. But prior experience is definitely helpful and the time to build the third compiler was less than one fifth that for the first one.

One proof tells us more than any finite amount of testing. If a correct proof can be obtained. This latter problem can be solved by the code file: Each subtask is similarly decomposed until all tasks are expressed within a programming language. This is referred to as the bottom-up approach.

The design process consists essentially of taking a proposed solution and successively refining it until an executable program is achieved. The initial solution may be expressed in English or some form of mathematical notation. Suppose we devise a program for sorting a set of n given by the following 1 distinct integers. A look ahead to problems which may arise later is often useful. This method of design is called the top-down approach.

At this level the formulation is said to be abstract because it contains no details regarding how the objects will be represented and manipulated in a computer.

If possible the designer attempts to partition the solution into logical subtasks. We are now ready to give a second refinement of the solution: One solution is to store the values in an array in such a way that the i-th integer is stored in the i-th array position. One of the simplest solutions is "from those integers which remain unsorted. Underlying all of these strategies is the assumption that a language exists for adequately describing the processing of data at several abstract levels.

Let us examine two examples of top-down program development. Experience suggests that the top-down approach should be followed when creating a program. There now remain two clearly defined subtasks: Eventually A n is compared to the current minimum and we are done.

We first note that for any i. We observe at this point that the upper limit of the for-loop in line 1 can be changed to n. A j t The first subtask can be solved by assuming the minimum is A i. From the standpoint of readability we can ask if this program is good. Is there a more concise way of describing this algorithm which will still be as easy to comprehend?

Substituting while statements for the for loops doesn't significantly change anything.. Let us develop another program. By making use of the fact that the set is sorted we conceive of the following efficient method: There are three possibilities. Continue in this way by keeping two pointers.

We assume that we have n 1 distinct integers which are already sorted and stored in the array A 1: Below is one complete version. This method is referred to as binary search. Note how at each stage the number of elements in the remaining set is decreased by about one half. There are many more that we might produce which would be incorrect. In fact there are at least six different binary search programs that can be produced which are all correct.

Whichever version we choose. For instance we could replace the while loop by a repeat-until statement with the same English condition. Part of the freedom comes from the initialization step. Given a set of instructions which perform a logical operation.. Recursion We have tried to emphasize the need to structure a program to make it easier to achieve the goals of readability and correctness.

As we enter this loop and as long as x is not found the following holds: Unfortunately a complete proof takes us beyond our scope but for those who wish to pursue program proving they should consult our references at the end of this chapter.

Actually one of the most useful syntactical features for accomplishing this is the procedure. The procedure name and its parameters file: Of course.. When is recursion an appropriate mechanism for algorithm exposition? One instance is when the problem itself is recursively defined.

For these reasons we introduce recursion here. This view of the procedure implies that it is invoked. What this fails to stress is the fact that procedures may call themselves direct recursion before they are done or they may call other procedures which again invoke the calling procedure indirect recursion..

Factorial fits this category. These recursive mechanisms are extremely powerful. This is unfortunate because any program that can be written using assignment. Most students of computer science view recursion as a somewhat mystical technique which only is useful for some very special class of problems such as computing factorials or Ackermann's function.

Given the input-output specifications of a procedure.. The answer is obtained by printing i a followed by all permutations of b. Given a set of n 1 elements the problem is to print all possible permutations of this set. Then try to do one or more of the exercises at the end of this chapter which ask for recursive procedures.

It is easy to see that given n elements there are n! A is a character string e. A simple algorithm can be achieved by looking at the case of four elements a. B file: It implies that we can solve the problem for a set with n elements if we had an algorithm which worked on n. This may sound strange. But for now we will content ourselves with examining some simple.

This gives us the following set of three procedures. To rewrite it recursively the first thing we do is to remove the for loops and express the algorithm using assignment. The main purpose is to make one more familiar with the execution of a recursive procedure. Suppose we start with the sorting algorithm presented in this section. We will see several important examples of such structures.. Another instance when recursion is invaluable is when we want to describe a backtracking procedure.

Every place where a ''go to label'' appears. The effect of increasing k by one and restarting the procedure has essentially the same effect as the for loop.

Now let us trace the action of these procedures as they sort a set of five integers When a procedure is invoked an implicit branch to its beginning is made. These two procedures use eleven lines while the original iterative version was expressed in nine lines. Notice how in MAXL2 the fourth parameter k is being changed. Procedure MAXL2 is also directly reculsive. Thus a recursive call of a file: There are other criteria for judging programs which have a more direct relationship to performance.

In section 4. The above criteria are all vitally important when it comes to writing software.. Also in that section are several recursive procedures. The first is the amount of time a single execution will take. The parameter mechanism of the procedure is a form of assignment. These have to do with computing time and storage requirements of the algorithms. The product of these numbers will be the total time taken by this statement.

Performance evaluation can be loosely divided into 2 major phases: The second statistic is called the frequency count. Hopefully this more subtle approach will gradually infect your own program writing habits so that you will automatically strive to achieve these goals. Both of these are equally important. Though we will not be discussing how to reach these goals. There are many criteria upon which we can judge a program. First consider a priori estimation. We would like to determine two numbers for this statement.

Rules are also given there for eliminating recursion. It is impossible to determine exactly how much time it takes to execute any command unless we have the following information: Parallelism will not be considered. In both cases the exact times we would determine would not apply to many machines or to any machine. Neither of these alternatives seems attractive. All these considerations lead us to limit our goals for an a priori analysis. Consider the three examples of Figure 1. The anomalies of machine configuration and language will be lumped together when we do our experimental studies.

Another approach would be to define a hypothetical machine with imaginary execution times. One of the hardest tasks in estimating frequency counts is to choose adequate samples of data. It is possible to determine these figures by choosing a real machine and an existing compiler. The program on the following page takes any non-negative integer n and prints the value Fn. In the program segment of figure 1.

Each new term is obtained by taking the sum of the two previous terms. In our analysis of execution we will be concerned chiefly with determining the order of magnitude of an algorithm. Now 1.

In general To clarify some of these ideas.. This means determining those statements which may have the greatest frequency count. In program b the same statement will be executed n times and in program c n2 times assuming n 1. Then its frequency count is one. The Fibonacci sequence starts as 0. To determine the order of magnitude.. Three simple programs for frequency counting.. A complete set would include four cases: Below is a table which summarizes the frequency counts for the first three cases.

Though 2 to n is only n. None of them exercises the program very much. Step Frequency Step Frequency 2 3 4 5 6 7 1 1 1 0 1 0 1 9 10 11 12 13 14 15 2 n n-1 n-1 n-1 n-1 1 file: We can summarize all of this with a table. At this point the for loop will actually be entered. Steps 1. These may have different execution counts. Both commands in step 9 are executed once. The for statement is really a combination of several statements.

O n is called linear. Execution Count for Computing Fn Each statement is counted once. This notation means that the order of magnitude is proportional to n. We will often write this as O n. For example n might be the number of inputs or the number of outputs or their sum or the magnitude of one of them.

O n2 is called quadratic. O n log n is better than O n2 but not as good as O n. The reason for this is that as n increases the time for the second algorithm will get far worse than the time for the first.

O n3 is called cubic. We write O 1 to mean a computing time which is a constant. These seven computing times. If an algorithm takes time O log n it is faster. For example. O log n. When we say that the computing time of an algorithm is O g n we mean that its execution takes no more than a constant times g n. If we have two algorithms which perform the same task. Often one can trade space for time. An algorithm which is exponential will work only for very small inputs.

Another valid performance measure of an algorithm is the space it requires. Using big-oh notation. On the other hand. For exponential algorithms. Notice how the times O n and O n log n grow much more slowly than the others. We will see cases of this in subsequent chapters. Given an algorithm. For small data sets.

Then a performance profile can be gathered using real time calculation. In practice these constants depend on many factors.. This shows why we choose the algorithm with the smaller order of magnitude. For large data sets. Figures When n is odd H. Coxeter has given a simple rule for generating a magic square: A magic square is an n x n matrix of the integers 1 to n2 such that the sum of every row. It emphasizes that the variables are thought of as pairs and are changed as a unit.

The statement i. The file: Academic Press. Fundamental Algorithms. Thus each statement within the while loop will be executed no more than n2. Special Issue: Since there are n2 positions in which the algorithm must place a number.

For a discussion of tools and procedures for developing very large software systems see Practical Strategies for Developing Large Software Systems.

For a discussion of the more abstract formulation of data structures see "Toward an understanding of data structures" by J. ACM Computing Surveys.

Kernighan and P. The while loop is governed by the variable key which is an integer variable initialized to 2 and increased by one each time through the loop. For a discussion of good programming techniques see Structured Programming by O. The Elements of Programming Style by B. For this application it is convenient to number the rows and columns from zero to n.

The magic square is represented using a two dimensional array having n rows and n column. For a further discussion of program proving see file: Can you think of a clever meaning for S. Describe the flowchart in figure 1. American Mathematical Society. Can you do this without using the go to? Now make it into an algorithm. Both do not satisfy one of the five criteria of an algorithm.

Look up the word algorithm or its older form algorism in the dictionary.? Concentrate on the letter K first. How would you handle people with the same last name. Discuss how you would actually represent the list of name and telephone number pairs in a real machine. Which criteria do they violate?

Consider the two statements: For instance.. What is the computing time of your method? Strings x and y remain unchanged. Determine when the second becomes larger than the first. String x is unchanged. The rule is: If x occurs Given n boolean variables x Try writing this without using the go to statement.

Implement these procedures using the array facility. Determine how many times each statement is executed. List as many rules of style in programming that you can think of that you would be willing to follow yourself. Represent your answer in the array ANS 1: NOT X:: Take any version of binary search. Prove by induction: Using the notation introduced at the end of section 1. Trace the action of the procedure below on the elements 2.

Write a recursive procedure for computing this function. Given n. If S is a set of n elements the powerset of S is the set of all possible subsets of S. Tower of Hanoi There are three towers and sixty four disks of different diameters placed on the first tower. Write a recursive procedure for computing the binomial coefficient where. The pigeon hole principle states that if a function f has n distinct inputs but less than n distinct outputs then there exists two inputs a. Then write a nonrecursive algorithm for computing Ackermann's function.

Ackermann's function A m. Analyze the time and space requirements of your algorithm. Analyze the computing time of procedure SORT as given in section 1. Write a recursive procedure to compute powerset S.

Write a recursive procedure which prints the sequence of moves which accomplish this task. The disks are in order of decreasing diameter as one scans up the tower. Give an algorithm which finds the values a. Monks were reputedly supposed to move the disks from tower 1 to tower 3 obeying the rules: It is true that arrays are almost always implemented by using consecutive memory.

Using our notation this object can be defined as: If one asks a group of programmers to define an array. Therefore it deserves a significant amount of attention. In mathematical terms we call this a correspondence or a mapping. For arrays this means we are concerned with only two operations which retrieve and store values.

STORE is used to enter new index-value pairs. The array is often the only means for structuring data which is provided in a programming language.. For each index which is defined. This is unfortunate because it clearly reveals a common point of confusion.

If we interpret the indices to be n-dimensional. If we consider an ordered list more abstractly. If we restrict the index values to be integers. There are a variety of operations that are performed on these lists.

Ace or the floors of a building basement. Notice how the axioms are independent of any representation scheme. In section 2. These operations include: This we will refer to as a sequential mapping.. It is only operations v and vi which require real effort. This gives us the ability to retrieve or modify the values of random elements in the list in a constant amount of time..

By "symbolic. It is precisely this overhead which leads us to consider nonsequential mappings of ordered lists into arrays in Chapter 4. The problem calls for building a set of subroutines which allow for the manipulation of symbolic polynomials.

We can access the list element values in either direction by changing the subscript values in a controlled way.. It is not always necessary to be able to perform all of these operations. In the study of data structures we are interested in ways of representing ordered lists so that these operations can be carried out efficiently. Let us jump right into a problem requiring ordered lists which we will solve by using one dimensional arrays.

Perhaps the most common way to represent an ordered list is by an array where we associate the list element ai with the array index i. This problem has become the classical example for motivating the use of list processing techniques which we will see in later chapters. Insertion and deletion using sequential allocation forces us to move some of the remaining elements so the sequential mapping is preserved in its proper form.

The first step is to consider how to define polynomials as a computer structure. However this is not an appropriate definition for our purposes. A complete specification of the data structure polynomial is now given. For a mathematician a polynomial is a sum of terms where each term has the form axe.

When defining a data object one must decide what functions will be available. MULT poly. We will also need input and output routines and some suitable format for preparing polynomials as input. These assumptions are decisions of representation. Suppose we wish to remove from P those terms having exponent one. Then we would write REM P. Notice the absense of any assumptions about the order of exponents. Now we can make some representation decisions.

Note how trivial the addition and multiplication operations have become. These axioms are valuable in that they describe the meaning of each operation concisely and without implying an implementation. Now assuming a new function EXP poly exp which returns the leading exponent of poly. EXP B file: COEF B. Exponents should be unique and in decreasing order is a very reasonable first decision.

EXP B. This representation leads to very simple algorithms for addition and multiplication.. COEF A. But are there any disadvantages to this representation? Hopefully you have already guessed the worst one. B REM B. With these insights. Since the tests within the case statement require two terms. EXP A. The case statement determines how the exponents are related and performs the proper action.. We have avoided the need to explicitly store the exponent of each term and instead we can deduce its value by knowing our position in the list and the degree.

EXP B: C A end end insert any remaining terms in A or B into C The basic loop of this algorithm consists of merging the terms of the two polynomials. As for storage. But scheme 1 could be much more wasteful. It will require a vector of length Then for each term there are two entries representing an exponent-coefficient pair. In general. In the worst case. Is this method any better than the first scheme? The first entry is the number of nonzero terms. If all of A's coefficients are nonzero.

Basic algorithms will need to be more complex because we must check each exponent before we handle its coefficient.. Suppose we take the polynomial A x above and keep only its nonzero coefficients. This is a practice you should adopt in your own coding. It is natural to carry out this analysis in terms of m and n.

Comments appear to the right delimited by double slashes. Notice how closely the actual program matches with the original design. The procedure has parameters which are polynomial or array names.

Statement two is a shorthand way of writing r The basic iteration step is governed by a while loop. Three pointers p. Blocks of statements are grouped together using square brackets.. The code is indented to reinforce readability and to reveal more clearly the scope of reserved words. The assignments of lines 1 and 2 are made only once and hence contribute O 1 to the overall computing time.

We are making these four procedures available to any user who wants to manipulate polynomials. Taking the sum of all of these steps. He would include these subroutines along with a main procedure he writes himself. Each iteration of this while loop requires O 1 time. This hypothetical user may have many polynomials he wants to compute and he may not know their sizes.

Supplementary Texts. Michael T. Goodrich and Roberto Tamassia, Data Structures and. Algorithms in JAVA Data Structures Reg. Question Paper Code: Hybrid and Custom Data Structures: Without some form of abstraction, one Sartaj 1.

With more than 15 years of experience in the data center industry, Gustavo Mill, underwent seven editions The eighth and ninth edition are reprints of the seventh edition.

Acrylic on paper Vintage CIA sweatshirt with patches variable. Communication of Complex Data Structures Abstract. Communicating complex data structures, that is Converting dialects is a complicated process, but For many years a data structures course has been taught in computer science Newell, C. Shaw, and H. Simon , LISP 1. Table of Contents www. Often it is regarded as a central course of the curriculum. It is fascinating and instructive to trace the history of how the subject matter for this course has changed.

Back in the middle's the course was not entitled Data Structures but perhaps List Processing Languages. Farber, R. Griswold, and I. Knuth appeared. His thesis was that list processing was not a magical thing that could only be accomplished within a specially designed system. Instead, he argued that the same techniques could be carried out in almost any language and he shifted the emphasis to efficient algorithm design.

The new strategy was to explicitly construct a representation such as linked lists within a set of consecutive storage locations and to describe the algorithms by using English plus assembly language. Progress in the study of data structures and algorithm design has continued. Out of this recent work has come many good ideas which we believe should be presented to students of computer science.

It is our purpose in writing this book to emphasize those trends which we see as especially valuable and long lasting. The most important of these new concepts is the need to distinguish between the specification of a data structure and its realization within an available programming language.

This distinction has been mostly blurred in previous books where the primary emphasis has either been on a programming language or on representational techniques. Our attempt here has been to separate out the specification of the data structure from its realization and to show how both of these processes can be successfully accomplished.

The specification stage requires one to concentrate on describing the functioning of the data structure without concern for its implementation.

This can be done using English and mathematical notation, but here we introduce a programming notation called axioms. The resulting implementation independent specifications valuable in two ways: To describe a data structure in a representation independent way one needs a syntax.

This can be seen at the end of section 1. This book also seeks to teach the art of analyzing algorithms but not at the cost of undue mathematical sophistication.

The value of an implementation ultimately relies on its resource utilization: This implies that the student needs to be capable of analyzing these factors.

A great many analyses have appeared in the literature, yet from our perspective most students don't attempt to rigorously analyze their programs. The data structures course comes at an opportune time in their training to advance and promote these ideas. For every algorithm that is given here we supply a simple, yet rigorous worst case analysis of its behavior. In some cases the average computing time is also file: The growth of data base systems has put a new requirement on data structures courses, namely to cover the organization of large files.

Also, many instructors like to treat sorting and searching because of the richness of its examples of data structures and its practical application. The choice of our later chapters reflects this growing interest.

One especially important consideration is the choice of an algorithm description language. Such a choice is often complicated by the practical matters of student background and language availability. Our decision was to use a syntax which is particularly close to ALGOL, but not to restrict ourselves to a specific language.

This gives us the ability to write very readable programs but at the same time we are not tied to the idiosyncracies of a fixed language. Wherever it seemed advisable we interspersed English descriptions so as not to obscure the main pointof an algorithm. For those who have only FORTRAN available, the algorithms are directly translatable by the rules given in the appendix and a translator can be obtained see appendix A.

On the other hand, we have resisted the temptation to use language features which automatically provide sophisticated data structuring facilities. We have done so on several grounds. One reason is the need to commit oneself to a syntax which makes the book especially hard to read by those as yet uninitiated. Even more importantly, these automatic featules cover up the implementation detail whose mastery remains a cornerstone of the course.

The basic audience for this book is either the computer science major with at least one year of courses or a beginning graduate student with prior training in a field other than computer science. This book contains more than one semester's worth of material and several of its chapters may be skipped without harm. The following are two scenarios which may help in deciding what chapters should be covered.

He would cover chapters one through five skipping sections 2. Then, in whatever time was left chapter seven on sorting was covered. In the first quarter's data structure course, chapters one through three are lightly covered and chapters four through six are completely covered. The second quarter starts with chapter seven which provides an excellent survey of the techniques which were covered in the previous quarter.

Then the material on external sorting, symbol tables and files is sufficient for the remaining time. Note that the material in chapter 2 is largely mathematical and can be skipped without harm. The paradigm of class presentation that we have used is to begin each new topic with a problem, usually chosen from the computer science arena.

Once defined, a high level design of its solution is made and each data structure is axiomatically specified. A tentative analysis is done to determine which operations are critical. Implementations of the data structures are then given followed by an attempt at verifying file: The finishedalgorithm in the book is examined followed by an argument concerning its correctness.

Then an analysis is done by determining the relevant parameters and applying some straightforward rules to obtain the correct computing time formula. In summary, as instructors we have tried to emphasize the following notions to our students: In addition there are two underlying currents which, though not explicitly emphasized are covered throughout. The first is the notion of writing nicely structured programs. For all of the programs contained herein we have tried our best to structure them appropriately.

We hope that by reading programs with good style the students will pick up good writing habits. A nudge on the instructor's part will also prove useful. The second current is the choice of examples. We have tried to use those examples which prove a point well, have application to computer programming, and exhibit some of the brightest accomplishments in computer science.

At the close of each chapter there is a list of references and selected readings. These are not meant to be exhaustive. They are a subset of those books and papers that we found to be the most useful. Otherwise, they are either historically significant or develop the material in the text somewhat further. Many people have contributed their time and energy to improve this book.

For this we would like to thank them. We wish to thank Arvind [sic], T. Gonzalez, L. Landweber, J. Misra, and D. Wilczynski, who used the book in their own classes and gave us detailed reactions. Thanks are also due to A. Agrawal, M. Cohen, A. Howells, R. Istre, D. Ledbetter, D. Musser and to our students in CS , CSci and who provided many insights. For administrative and secretarial help we thank M.

Eul, G. Lum, J. Matheson, S. Moody, K. Pendleton, and L. To the referees for their pungent yet favorable comments we thank S. Gerhart, T.

Standish, and J. Finally, we would like to thank our institutions, the University of Southern California and the University of Minnesota, for encouraging in every way our efforts to produce this book. Ellis Horowitz Sartaj Sahni Preface to the Ninth Printing We would like to acknowledge collectively all of the individuals who have sent us comments and corrections since the book first appeared.

For this printing we have made many corrections and improvements. October l file: One often quoted definition views computer science as the study of algorithms. This study encompasses four distinct areas: The goal is to study various forms of machine fabrication and organization so that algorithms can be effectively carried out. At one end are the languages which are closest to the physical machine and at the other end are languages designed for sophisticated problem solving.

One often distinguishes between two phases of this area: The first calls for methods for specifying the syntax and semantics of a language. The second requires a means for translation into a more basic set of commands. Abstract models of computers are devised so that these properties can be studied.

This was realized as far back as by Charles Babbage, the father of computers. An algorithm's behavior pattern or performance profile is measured in terms of the computing time and space that are consumed while the algorithm is processing.

Questions such as the worst and average time and how often they occur are typical. We see that in this definition of computer science, "algorithm" is a fundamental notion.

Thus it deserves a precise definition. The dictionary's definition "any mechanical or recursive computational procedure" is not entirely satisfying since these terms are not basic enough. An algorithm is a finite set of instructions which, if followed, accomplish a particular task. In addition every algorithm must satisfy the following criteria: It is not enough that each operation be definite as in iii , but it must also be feasible.

In formal computer science, one distinguishes between an algorithm, and a program. A program does not necessarily satisfy condition iv. One important example of such a program for a computer is its operating system which never terminates except for system crashes but continues in a wait loop until more jobs are entered.

In this book we will deal strictly with programs that always terminate.

Hence, we will use these terms interchangeably. An algorithm can be described in many ways. A natural language such as English can be used but we must be very careful that the resulting instructions are definite condition iii. An improvement over English is to couple its use with a graphical form of notation such as flowcharts. This form places each processing step in a "box" and uses arrows to indicate the next step.

Different shaped boxes stand for different kinds of operations. All this can be seen in figure 1. The point is that algorithms can be devised for many common activities.

Have you studied the flowchart? Then you probably have realized that it isn't an algorithm at all! Which properties does it lack? Returning to our earlier definition of computer science, we find it extremely unsatisfying as it gives us no insight as to why the computer is revolutionizing our society nor why it has made us re-examine certain basic assumptions about our own role in the universe.

While this may be an unrealistic demand on a definition even from a technical point of view it is unsatisfying. The definition places great emphasis on the concept of algorithm, but never mentions the word "data".

If a computer is merely a means to an end, then the means may be an algorithm but the end is the transformation of data. That is why we often hear a computer referred to as a data processing machine. Raw data is input and algorithms are used to transform it into refined data. So, instead of saying that computer science is the study of algorithms, alternatively, we might say that computer science is the study of data: Figure 1.

Flowchart for obtaining a Coca-Cola There is an intimate connection between the structuring of data, and the synthesis of algorithms. In fact, a data structure and an algorithm should be thought of as a unit, neither one making sense without the other. For instance, suppose we have a list of n pairs of names and phone numbers a1,b1 a2,b2 , This task is called searching. Just how we would write such an algorithm critically depends upon how the names and phone numbers are stored or structured.

One algorithm might just forge ahead and examine names, a1,a2,a3, This might be fine in Oshkosh, but in Los Angeles, with hundreds of thousands of names, it would not be practical. If, however, we knew that the data was structured so that the names were in alphabetical order, then we could do much better.

We could make up a second list which told us for each letter in the alphabet, where the first name with that letter appeared. For a name beginning with, say, S, we would avoid having to look at names beginning with other letters. So because of this new structure, a very different algorithm is possible. Other ideas for algorithms become possible when we realize that we can organize the data as we wish. We will discuss many more searching strategies in Chapters 7 and 9.

Therefore, computer science can be defined as the study of data, its representation and transformation by a digital computer. The goal of this book is to explore many different kinds of data objects.

For each object, we consider the class of operations to be performed and then the way to represent this object so that these operations may be efficiently carried out. This implies a mastery of two techniques: The pedagogical style we have chosen is to consider problems which have arisen often in computer applications.

For each problem we will specify the data object or objects and what is to be accomplished. After we have decided upon a representation of the objects, we will give a complete algorithm and analyze its computing time.

After reading through several of these examples you should be confident enough to try one on your own. There are several terms we need to define carefully before we proceed. These include data structure, data object, data type and data representation. These four terms have no standard meaning in computer science circles, and they are often used interchangeably. A data type is a term which refers to the kinds of data that variables may "hold" in a programming language.

With every programming language there is a set of built-in data types. This means that the language allows variables to name data of that type and file: Some data types are easy to provide because they are already built into the computer's machine language instruction set. Integer and real arithmetic are examples of this. Other data types require considerably more effort to implement.

In some languages, there are features which allow one to construct combinations of the built-in types. However, it is not necessary to have such a mechanism. All of the data structures we will see here can be reasonably built within a conventional programming language.

Data object is a term referring to a set of elements, say D. Thus, D may be finite or infinite and if D is very large we may need to devise special ways of representing its elements in our computer. The notion of a data structure as distinguished from a data object is that we want to describe not only the set of objects, but the way they are related.

Saying this another way, we want to describe the set of operations which may legally be applied to elements of the data object. This implies that we must specify the set of operations and show how they work.

To be more precise lets examine a modest example. The following notation can be used: SUCC stands for successor. The rules on line 8 tell us exactly how the addition operation works. For example if we wanted to add two and three we would get the following sequence of expressions: In practice we use bit strings which is a data structure that is usually provided on our computers.

But however the ADD operation is implemented, it must obey these rules. Hopefully, this motivates the following definition. A data structure is a set of domains , a designated domain , a set of functions and a file: The triple www. The form in which we choose to write the axioms is important.

Our goal here is to write the axioms in a representation independent way. Then, we discuss ways of implementing the functions using a conventional programming language. An implementation of a data structure d is a mapping from d to a set of other data structures e. This mapping specifies how every object of d is to be represented by the objects of e. Secondly, it requires that every function of d must be written using the functions of the implementing data structures e.

Thus we say that integers are represented by bit strings, boolean is represented by zero and one, an array is represented by a set of consecutive words in memory. In current parlance the triple is referred to as an abstract data type. It is called abstract precisely because the axioms do not imply a form of representation.

Another way of viewing the implementation of a data structure is that it is the process of refining an abstract data type until all of the operations are expressible in terms of directly executable functions. But at the first stage a data structure should be designed so that we know what it does, but not necessarily how it will do it.

This division of tasks, called specification and implementation, is useful because it helps to control the complexity of the entire process. Though some of these are more preferable than others, the choice of a specific language leaves us with many difficulties. First of all, we wish to be able to write our algorithms without dwelling on the idiosyncracies of a given language.

Secondly, some languages have already provided the mechanisms we wish to discuss. Thus we would have to make pretense to build up a capability which already exists. Finally, each language has its followers and its detractors. We would rather not have any individual rule us out simply because he did not know or, more particularly, disliked to use the language X. Furthermore it is not really necessary to write programs in a language for which a compiler exists. Instead we choose to use a language which is tailored to describing the algorithms we want to write.

Most importantly, the language we use will be close enough to many of the languages mentioned before so that a hand translation will be relatively easy to accomplish. Moreover, one can easily program a translator using some existing, but more primitive higher level language as the output see Appendix A. Nevertheless, computerniks still try to attach a meaning.

Several cute ideas have been suggested, such as Structured Programming: The way to assign values is by the assignment statement variable expression.

In addition to the assignment statement, SPARKS includes statements for conditional testing, iteration, input-output, etc. Several such statements can be combined on a single line if they are separated by a semi-colon. Expressions can be either arithmetic, boolean or of character type. In the boolean case there can be only one of two values, true or false. In order to produce these values, the logical operators and, or, not are provided, plus the relational operators file: If S1 or S2 contains more than one statement, these will be enclosed in square brackets.

Brackets must be used to show how each else corresponds to one if. The meaning of this statement is given by the flow charts: We will assume that conditional expressions are evaluated in "short circuit" mode; given the boolean expression cond1 or cond2 , if condl is true then cond2 is not evaluated; or, given condl and cond2 , if cond1 is false then cond2 is not evaluated.

To accomplish iteration, several statements are available. One of them is while cond do S end where cond is as before, S is as S1 before and the meaning is given by It is well known that all "proper" programs can be written using only the assignment, conditional and while statements.

This result was obtained by Bohm and Jacopini. Though this is very interesting from a theoretical viewpoint, we should not take it to mean that this is the way to program.

On the contrary, the more expressive our languages are, the more we can accomplish easily. So we will provide other statements such as a second iteration statement, the repeat-until, repeat S file: Another iteration statement is loop S forever which has the meaning As it stands, this describes an infinite loop! However, we assume that this statement is used in conjunction with some test within S which will cause an exit.

One way of exiting such a loop is by using a go to label statement which transfers control to "label. A more restricted form of the go to is the command exit which will cause a transfer of control to the first statement after the innermost loop which contains it.

This looping statement may be a while, repeat, for or a loop-forever. A variable or a constant is a simple form of an expression. The semantics is easily described by the file: The else clause is optional. The expr may be omitted in which case a return is made to the calling procedure.

The execution of an end at the end of procedure implies a return. A procedure may be invoked by using a call statement call NAME parameter list Procedures may call themselves, direct recursion, or there may be a sequence resulting in indirect recursion. Though recursion often carries with it a severe penalty at execution time, it remains all elegant way to describe many computing processes.

This penalty will not deter us from using recursion. Many such programs are easily translatable so that the recursion is removed and efficiency achieved. All procedures are treated as external, which means that the only means for communication between them is via parameters. This may be somewhat restrictive in practice, but for the purpose of exposition it helps to list all variables explicitly, as either local or parameter. The association of actual to formal parameters will be handled using the call by reference rule.

This means that at run time the address of each parameter is passed to the called procedure. Parameters which are constants or values of expressions are stored into internally generated words whose addresses are then passed to the procedure.

We avoid the problem of defining a "format" statement as we will need only the simplest form of input and output. The command stop halts execution of the currently executing procedure. Comments may appear anywhere on a line enclosed by double slashes, e. An n-dimensional array A with lower and upper bounds li, ui, 1 i n may be declared by using the syntax declare A l1: We have avoided introducing the record or structure concept.

These are often useful features and when available they should be used. However, we will persist in building up a structure from the more elementary array concept. Since most of the SPARKS programs will be read many more times than they will be executed, we have tried to make the code readable. This is a goal which should be aimed at by everyone who writes programs. The SPARKS language is rich enough so that one can create a good looking program by applying some simple rules of style.

Avoid sentences like ''i is increased by one. See the book The Elements of Programming Style by Kernighan and Plauger for more examples of good rules of programming. This method uses the philosophy: Surprisingly, this method is in wide use today, with the result that an average programmer on an average job turns out only between five to ten lines of correct code per day.

We hope your productivity will be greater. But to improve requires that you apply some discipline to the process of creating programs. To understand this process better, we consider it as broken up into five phases: Make sure you understand the information you are given the input and what results you are to produce the output. Try to write down a rigorous description of the input and output which covers all cases. You are now ready to proceed to the design phase.

Designing an algorithm is a task which can be done independently of the programming language you eventually plan to use. In fact, this is desirable because it means you can postpone questions concerning how to represent your data and what a particular statement looks like and concentrate on the order of processing. You may have several data objects such as a maze, a polynomial, or a list of names. For each object there will be some basic operations to perform on it such as print the maze, add two polynomials, or find a name in the list.

Assume that these operations already exist in the form of procedures and write an algorithm which solves the problem according to the requirements. Use a notation which is natural to the way you wish to describe the order of processing.

Can you think of another algorithm? If so, write it down. Next, try to compare these two methods. It may already be possible to tell if one will be more desirable than the other. If you can't distinguish between the two, choose one to work on for now and we will return to the second version later. You must now choose representations for your data objects a maze as a two dimensional array of zeros and ones, a polynomial as a one dimensional array of degree and coefficients, a list of names possibly as an array and write algorithms for each of the operations on these objects.

The order in which you do this may be crucial, because once you choose a representation, the resulting algorithms may be inefficient. Modern pedagogy suggests that all processing which is independent of the data representation be written out first. By postponing the choice of how the data is stored we can try to isolate what operations depend upon the choice of data representation. You should consider alternatives, note them down and review them later.

Finally you produce a complete version of your first program. It is often at this point that one realizes that a much better program could have been built.

Perhaps you should have chosen the second design alternative or perhaps you have spoken to a friend who has done it better. This happens to industrial programmers as well. If you have been careful about keeping track of your previous work it may not be too difficult to make changes.

One of the criteria of a good design is file: It is usually hard to decide whether to sacrifice this first attempt and begin again or just continue to get the first version working.

Different situations call for different decisions, but we suggest you eliminate the idea of working on both at the same time. If you do decide to scrap your work and begin again, you can take comfort in the fact that it will probably be easier the second time. In fact you may save as much debugging time later on by doing a new version now. This is a phenomenon which has been observed in practice. The graph in figure 1. For each compiler there is the time they estimated it would take them and the time it actually took.

For each subsequent compiler their estimates became closer to the truth, but in every case they underestimated.

Unwarrented optimism is a familiar disease in computing. But prior experience is definitely helpful and the time to build the third compiler was less than one fifth that for the first one. Verification consists of three distinct aspects: Each of these is an art in itself.

Before executing your program you should attempt to prove it is correct. Proofs about programs are really no different from any other kinds of proofs, only the subject matter is different. If a correct proof can be obtained, then one is assured that for all possible combinations of inputs, the program and its specification agree.

Testing is the art of creating sample data upon which to run your program. If the program fails to respond correctly then debugging is needed to determine what went wrong and how to correct it.

One proof tells us more than any finite amount of testing, but proofs can be hard to obtain. Many times during the proving process errors are discovered in the code. The proof can't be completed until these are changed. This is another use of program proving, namely as a methodology for discovering errors. Finally there may be tools available at your computing center to aid in the testing process.

One such tool instruments your source code and then tells you for every data set: As a minimal requirement, the test data you construct should force every statement to execute and every condition to assume the value true and false at least once. One thing you have forgotten to do is to document. But why bother to document until the program is entirely finished and correct? Because for each procedure you made some assumptions about its input and output.

If you have written more than a few procedures, then you have already begun to forget what those assumptions were. If you note them down with the code, the problem of getting the procedures to work together will be easier to solve. The larger the software, the more crucial is the need for documentation. The previous discussion applies to the construction of a single procedure as well as to the writing of a large software system.

Let us concentrate for a while on the question of developing a single procedure which solves a specific task. This shifts our emphasis away from the management and integration of the file: The design process consists essentially of taking a proposed solution and successively refining it until an executable program is achieved. The initial solution may be expressed in English or some form of mathematical notation.

At this level the formulation is said to be abstract because it contains no details regarding how the objects will be represented and manipulated in a computer.

If possible the designer attempts to partition the solution into logical subtasks. Each subtask is similarly decomposed until all tasks are expressed within a programming language.

This method of design is called the top-down approach. Inversely, the designer might choose to solve different parts of the problem directly in his programming language and then combine these pieces into a complete program.

This is referred to as the bottom-up approach. Experience suggests that the top-down approach should be followed when creating a program.

However, in practice it is not necessary to unswervingly follow the method. A look ahead to problems which may arise later is often useful. Underlying all of these strategies is the assumption that a language exists for adequately describing the processing of data at several abstract levels. Let us examine two examples of top-down program development. Suppose we devise a program for sorting a set of n given by the following 1 distinct integers.

One of the simplest solutions is "from those integers which remain unsorted, find the smallest and place it next in the sorted list" This statement is sufficient to construct a sorting program. However, several issues are not fully specified such as where and how the integers are initially stored and where the result is to be placed.

One solution is to store the values in an array in such a way that the i-th integer is stored in the i-th array position, A i 1 i n. We are now ready to give a second refinement of the solution: There now remain two clearly defined subtasks: This latter problem can be solved by the code file: Eventually A n is compared to the current minimum and we are done. Let us develop another program. We assume that we have n 1 distinct integers which are already sorted and stored in the array A 1: By making use of the fact that the set is sorted we conceive of the following efficient method: There are three possibilities.

Continue in this way by keeping two pointers, lower and upper, to indicate the range of elements not yet tested. This method is referred to as binary search. Note how at each stage the number of elements in the remaining set is decreased by about one half. As we enter this loop and as long as x is not found the following holds: This, combined with the above assertion implies that x is not present.

Unfortunately a complete proof takes us beyond our scope but for those who wish to pursue program proving they should consult our references at the end of this chapter. Recursion We have tried to emphasize the need to structure a program to make it easier to achieve the goals of readability and correctness.

Actually one of the most useful syntactical features for accomplishing this is the procedure. Given a set of instructions which perform a logical operation, perhaps a very complex and long operation, they can be grouped together as a procedure. The procedure name and its parameters file: Given the input-output specifications of a procedure, we don't even have to know how the task is accomplished, only that it is available. This view of the procedure implies that it is invoked, executed and returns control to the appropriate place in the calling procedure.

What this fails to stress is the fact that procedures may call themselves direct recursion before they are done or they may call other procedures which again invoke the calling procedure indirect recursion. These recursive mechanisms are extremely powerful, but even more importantly, many times they can express an otherwise complex process very clearly. For these reasons we introduce recursion here. Most students of computer science view recursion as a somewhat mystical technique which only is useful for some very special class of problems such as computing factorials or Ackermann's function.

This is unfortunate because any program that can be written using assignment, the if-then-else statement and the while statement can also be written using assignment, if-then-else and recursion.

Of course, this does not say that the resulting program will necessarily be easier to understand. However, there are many instances when this will be the case. When is recursion an appropriate mechanism for algorithm exposition? One instance is when the problem itself is recursively defined. Given a set of n 1 elements the problem is to print all possible permutations of this set. It is easy to see that given n elements there are n!

A simple algorithm can be achieved by looking at the case of four elements a,b,c,d. The answer is obtained by printing i a followed by all permutations of b,c,d ii b followed by all permutations of a,c,d iii c followed by all permutations of b,a,d iv d followed by all permutations of b,c,a The expression "followed by all permutations" is the clue to recursion. It implies that we can solve the problem for a set with n elements if we had an algorithm which worked on n - 1 elements.

A is a character string e. Then try to do one or more of the exercises at the end of this chapter which ask for recursive procedures. We will see several important examples of such structures, especially lists in section 4. Another instance when recursion is invaluable is when we want to describe a backtracking procedure. But for now we will content ourselves with examining some simple, iterative programs and show how to eliminate the iteration statements and replace them by recursion.

This may sound strange, but the objective is not to show that the result is simpler to understand nor more efficient to execute. The main purpose is to make one more familiar with the execution of a recursive procedure. Suppose we start with the sorting algorithm presented in this section.

To rewrite it recursively the first thing we do is to remove the for loops and express the algorithm using assignment, if-then-else and the go-to statement. Every place where a ''go to label'' appears, we replace that statement by a call of the procedure associated with that label. This gives us the following set of three procedures. Procedure MAXL2 is also directly reculsive.

These two procedures use eleven lines while the original iterative version was expressed in nine lines; not much of a difference.

Notice how in MAXL2 the fourth parameter k is being changed. The effect of increasing k by one and restarting the procedure has essentially the same effect as the for loop.

Now let us trace the action of these procedures as they sort a set of five integers When a procedure is invoked an implicit branch to its beginning is made. Thus a recursive call of a file: The parameter mechanism of the procedure is a form of assignment.

In section 4. Also in that section are several recursive procedures, followed in some cases by their iterative equivalents. Rules are also given there for eliminating recursion. There are many criteria upon which we can judge a program, for instance: The above criteria are all vitally important when it comes to writing software, most especially for large systems.

Though we will not be discussing how to reach these goals, we will try to achieve them throughout this book with the programs we write. Hopefully this more subtle approach will gradually infect your own program writing habits so that you will automatically strive to achieve these goals. There are other criteria for judging programs which have a more direct relationship to performance. These have to do with computing time and storage requirements of the algorithms. Performance evaluation can be loosely divided into 2 major phases: Both of these are equally important.

First consider a priori estimation. We would like to determine two numbers for this statement. The first is the amount of time a single execution will take; the second is the number of times it is executed. The product of these numbers will be the total time taken by this statement. The second statistic is called the frequency count, and this may file: One of the hardest tasks in estimating frequency counts is to choose adequate samples of data. It is impossible to determine exactly how much time it takes to execute any command unless we have the following information: It is possible to determine these figures by choosing a real machine and an existing compiler.

Another approach would be to define a hypothetical machine with imaginary execution times , but make the times reasonably close to those of existing hardware so that resulting figures would be representative.

Neither of these alternatives seems attractive. In both cases the exact times we would determine would not apply to many machines or to any machine.

Also, there would be the problem of the compiler, which could vary from machine to machine. Moreover, it is often difficult to get reliable timing figures because of clock limitations and a multi-programming or time sharing environment. Finally, the difficulty of learning another machine language outweighs the advantage of finding "exact" fictitious times. All these considerations lead us to limit our goals for an a priori analysis.

Instead, we will concentrate on developing only the frequency count for all statements. The anomalies of machine configuration and language will be lumped together when we do our experimental studies.

Parallelism will not be considered. Consider the three examples of Figure 1. Three simple programs for frequency counting.

Then its frequency count is one. In program b the same statement will be executed n times and in program c n2 times assuming n 1. In our analysis of execution we will be concerned chiefly with determining the order of magnitude of an algorithm. This means determining those statements which may have the greatest frequency count. To determine the order of magnitude, formulas such as often occur. In the program segment of figure 1.

The Fibonacci sequence starts as 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, Each new term is obtained by taking the sum of the two previous terms. The program on the following page takes any non-negative integer n and prints the value Fn. A complete set would include four cases: Below is a table which summarizes the frequency counts for the first three cases. None of them exercises the program very much. Notice, though, how each if statement has two parts: These may have different execution counts.

At this point the for loop will actually be entered. Steps 1, 2, 3, 5, 7 and 9 will be executed once, but steps 4, 6 and 8 not at all. Both commands in step 9 are executed once. Now, for n 2 how often is step 10 executed: Thus, steps 11, 12, 13 and 14 will be executed n - 1 times but step 10 will be done n times. We can summarize all of this with a table.

Step Frequency Step Frequency 1 9 2 2 1 10 n 3 1 11 n-1 4 0 12 n-1 5 1 13 n-1 6 0 14 n-1 7 1 15 1 file: Execution Count for Computing Fn Each statement is counted once, so step 9 has 2 statements and is executed once for a total of 2. Clearly, the actual time taken by each statement will vary. The for statement is really a combination of several statements, but we will count it as one.

We will often write this as O n , ignoring the two constants 5. This notation means that the order of magnitude is proportional to n. When we say that the computing time of an algorithm is O g n we mean that its execution takes no more than a constant times g n. For example n might be the number of inputs or the number of outputs or their sum or the magnitude of one of them. We write O 1 to mean a computing time which is a constant. O n is called linear, O n2 is called quadratic, O n3 is called cubic, and O 2n is called exponential.

If an algorithm takes time O log n it is faster, for sufficiently large n, than if it had taken O n. Similarly, O n log n is better than O n2 but not as good as O n. These seven computing times, O 1 , O log n , O n , O n log n , O n2 , O n3 , and O 2n are the ones we will see most often throughout the book.

If we have two algorithms which perform the same task, and the first has a computing time which is O n and the second O n2 , then we will usually take the first as superior. The reason for this is that as n increases the time for the second algorithm will get far worse than the time for the first.

This shows why we choose the algorithm with the smaller order of magnitude, but we emphasize that this is not the whole story. For small data sets, the respective constants must be carefully determined. In practice these constants depend on many factors, such as the language and the machine one is using.

Thus, we will usually postpone the establishment of the constant until after the program has been written. Then a performance profile can be gathered using real time calculation. Figures 1. Notice how the times O n and O n log n grow much more slowly than the others. For large data sets, algorithms with a complexity greater than O n log n are often impractical. An algorithm which is exponential will work only for very small inputs.

Given an algorithm, we analyze the frequency count of each statement and total the sum. Another valid performance measure of an algorithm is the space it requires. Often one can trade space for time, getting a faster algorithm but using more space. We will see cases of this in subsequent chapters. A magic square is an n x n matrix of the integers 1 to n2 such that the sum of every row, column and diagonal is the same.

When n is odd H. Coxeter has given a simple rule for generating a magic square: The statement i,j k,l is a shorthand way of writing i k; j l. It emphasizes that the variables are thought of as pairs and are changed as a unit.

The file: The magic square is represented using a two dimensional array having n rows and n column. For this application it is convenient to number the rows and columns from zero to n - 1 rather than from one to n. The while loop is governed by the variable key which is an integer variable initialized to 2 and increased by one each time through the loop.

Thus each statement within the while loop will be executed no more than n2 - 1 times and hence the computing time for MAGIC is O n2. Since there are n2 positions in which the algorithm must place a number, we see that O n2 is the best bound an algorithm could have. Fundamental Algorithms, by D. Knuth, vol. For a discussion of good programming techniques see Structured Programming by O.