text
stringlengths
1
1k
source
stringclasses
12 values
This book is licensed under a Creative Commons Attribution 3.0 License 2. Graphics primitives and environments Learning objectives: • turtle graphics • QuickDraw: A graphics toolbox • frame program • interactive graphics input/output • example: polyline input Turtle graphics: a basic environment Seymour Papert [Pap80]...
algorithms and data structures.pdf
current state: move(s) { take s unit steps in the direction you are facing } turn(d) { turn counterclockwise d degrees } The turtle's initial state is set by the following operations: moveto(x,y) { move to the position (x,y) in absolute coordinates } turnto(d) { face d degrees from due east } In addition, we can specif...
algorithms and data structures.pdf
different size and position. Thus we wish to turn a program fragment such as the circle approximation above into a reusable procedure. Algorithms and Data Structures 14 A Global Text
algorithms and data structures.pdf
2. Graphics primitives and environments Procedures as building blocks A program is built from components at many different levels of complexity. At the lowest level we have the constructs provided by the language we use: constants, variables, operators, expressions, and simple (unstructured) statements. At the next...
algorithms and data structures.pdf
consists of two parts with distinct purposes: 1. The heading specifies an important part of the procedure's external behavior through the list of formal parameters: namely, what type of data moves in and out of the procedure. 2. The body implements the action performed by the procedure, processing the input data and...
algorithms and data structures.pdf
the choice of formal parameters. Example: the long road toward a procedure “circle” Let us illustrate these issues by discussing design considerations for a procedure that draws a circle on the screen. The program fragment above for drawing a regular polygon is easily turned into procedure ngon(n,s: integer); { n = ...
algorithms and data structures.pdf
a := 360 div n; s := r · sin(a); { between inscribed and circumscribed polygons } for i := 1 to n do { move(s); turn(a) } end; This procedure places the burden of choosing n on the programmer. A more sophisticated, "adaptive" version might choose the number of sides on its own as a function of the radius of th...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License length 2 πr. We approximate it by drawing short-line segments, about 3 pixels long, thus needing about 2·r line segments. procedure circle(x, y, r: integer); { centered at (x, y); radius r} var a, s, i: integer; { angle, step, counter } begi...
algorithms and data structures.pdf
source of unnecessary work and errors. 2. The approximation of the circle by a polygon computed from vertex to vertex leads to rounding errors that accumulate. Thus the polygon may fail to close, in particular when using integer computation with its inherent large rounding error. 3. The procedure attempts to draw it...
algorithms and data structures.pdf
building a useful programming environment. In chapter 14 we return to this problem and present one possible goal of "the long road toward a procedure 'circle'". We now make a huge jump from the artificially small environments discussed so far to one of today's realistic programming environments for graphics QuickDr...
algorithms and data structures.pdf
and related figures: procedure FrameOval(r: Rect); procedure PaintOval(r: Rect); procedure EraseOval(r: Rect); procedure InvertOval(r: Rect); procedure FillOval(r: Rect; pat: Pattern); Each one inscribes an oval in an aligned rectangle r (sides parallel to the axes) so as to touch the four sides of r. If r is a squar...
algorithms and data structures.pdf
2. Graphics primitives and environments FrameOval draws an outline just inside the oval that fits inside the specified rectangle, using the current grafPort's pen pattern, mode, and size. The outline is as wide as the pen width and as tall as the pen height. It's drawn with the pnPat, according to the pattern trans...
algorithms and data structures.pdf
with the current grafPort's background pattern, 'InvertOval' complements the pixels: 'white' becomes 'black', and vice versa. 'FillOval' has an additional argument that specifies a pen pattern used for painting the interior. We may not need to know all of this in order to use one of these procedures, but we do need t...
algorithms and data structures.pdf
coordinate v that runs from top to bottom, and a second coordinate h that runs from left to right. (The reason for v running from top to bottom, rather than vice versa as used in math books, is compatibility with text coordinates where lines are naturally numbered from top to bottom.) The domain of v and h are the ...
algorithms and data structures.pdf
To understand the procedures of this section, the reader has to understand a few details about two key aspects of interactive graphics: • timing and synchronization of devices and program execution • how screen pictures are controlled at the pixel level 17
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Synchronization In interactive applications we often wish to specify a grid point by letting the user point the mouse-driven cursor to some spot on the screen. The 'procedure GetMouse(v, h)' returns the coordinates of the grid point where the cu...
algorithms and data structures.pdf
program execution with the user's clicks by programming busy waiting loops: repeat until Button; { waits for the button to be pressed } while Button do; { waits for the button to be released } The following procedure waits for the next click: procedure waitForClick; begin repeat until Button; while Button do end; Pi...
algorithms and data structures.pdf
PenPat(pat: Pattern)' [e.g. 'PenPat(gray)']. As 'white' is the default background, drawing in 'white' usually serves for erasing. The result of drawing also depends critically on the transfer mode 'pnMode', whose values include 'patCopy', 'patOr', and 'patXor'. A transfer mode is a boolean operation execu...
algorithms and data structures.pdf
2. Graphics primitives and environments • 'patXor' (exclusive-or, also known as "odd parity") sets the result to black iff exactly one of (screen pixel, pattern pixel) is black. A white pixel in the pen leaves the underlying screen pixel unchanged; a black pixel complements it. Thus a black pen inverts the screen. 'p...
algorithms and data structures.pdf
contains nothing but a few of the most useful input/output procedures, displays samples of their results, and conducts a minimal dialog so that the user can step through its execution. We call this a frame program because its real purpose is to facilitate development and testing of new procedures by embedding them i...
algorithms and data structures.pdf
one asks why they are introduced at all. 'GetPoint', for example, only converts integer mouse coordinates v, h into a point p with real coordinates. It enables us to refer to a point p without mentioning its coordinates explicitly. Thus, by bringing us closer to standard geometric notation, 'GetPoint' makes program...
algorithms and data structures.pdf
button were released at that moment. This rubber band keeps getting drawn and erased as it moves across other objects on the screen. The user should study a key detail in the procedure 'DragLine' that prevents other objects from being erased or modified as they collide with the ever-refreshed rubber ban...
algorithms and data structures.pdf
rubber-band routine: It alternates erasing (draw 'white') and drawing (draw 'black') the current rubber band, but in so doing it modifies other objects that share pixels with the rubber band. This is our first example of the use of the versatile exclusive-or; others will follow later in the book. program Frame; {...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License var c, p: point; r: real; { radius of a circle } L: lineSegment; procedure WaitForClick; begin repeat until Button; while Button do end; procedure GetPoint (var p: point); var v, h: integer; begin GetMouse(v, h); p.x := v; p.y := h { convert ...
algorithms and data structures.pdf
end; procedure DragLine(var L: lineSegment); begin repeat until Button; GetPoint(L.p1); L.p2 := L.p1; PenMode(patXor); while Button do begin DrawLine(L.p1, L.p2, black); { replace 'black' by 'white' above to get an artistic drawing tool } GetPoint(L.p2); DrawLine(L.p1, L.p2, black) end; PenMode(patCopy) end; { Dr...
algorithms and data structures.pdf
2. Graphics primitives and environments r := Dist(c, p); DrawCircle(c, r, black); end; PenMode(patCopy) end; { DragCircle } procedure Title; begin ShowText; { make sure the text window and … } ShowDrawing; { … the graphics window show on the screen } WriteLn('Frame program'); WriteLn('with simple graphics and intera...
algorithms and data structures.pdf
Let us illustrate the use of the frame program above in developing a new graphics procedure. We choose interactive polyline input as an example. A polyline is a chain of directed straight-line segments—the starting point of the next segment coincides with the endpoint of the previous one. 'Polyline' is the most u...
algorithms and data structures.pdf
example, the original frame program uses reals to represent coordinates of points, because most geometric computation is done that way. A polyline on a graphics screen only needs integers, so we changed the type 'point' to integer coordinates. At the moment, the code for polyline input is partly in the...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License p, q: point; function EqPoints (p, q: point): boolean; begin EqPoints := (p.x = q.x) and (p.y = q.y) end; function Dist (p, q: point): real; begin Dist := sqrt(sqr(p.x – q.x) + sqr(p.y – q.y)) end; procedure DrawLine (p, q: point; c: Pattern); b...
algorithms and data structures.pdf
end; { Title } procedure What; begin WaitForClick; GetMouse(p.x, p.y); stop := false; length := 0.0; PenMode(patXor); while not stop do begin NextLineSegment(p, q); stop := EqPoints(p, q); length := length + Dist(p, q); p := q end end; { What } procedure Epilog; begin WriteLn('Length of polyline = ', length);...
algorithms and data structures.pdf
2. Graphics primitives and environments 3. Implement your personal graphics frame program as described in “A graphics frame program”. Your effort will pay off in time saved later, as you will be using this program throughout the entire course. 23
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 3. Algorithm animation I hear and I forget, I see and I remember, I do and I understand. A picture is worth a thousand words—the art of presenting information in visual form. Learning objectives: • adding animation code to a program • examples of a...
algorithms and data structures.pdf
turning a channel selector, but controls the presentation at every step. He controls the flow not only with commands such as "faster", "slower", "repeat", "skip", "play this backwards", but more important, with a barrage of "what if?" questions. What if the area of this triangle becomes zero? What i...
algorithms and data structures.pdf
inputs as long as this variety is contained in an algorithmically tractable, narrow domain of discourse. It is not adept at tasks that require judgment, experience, or insight. By comparison, a speaker at the blackboard is slow and inaccurate and can only call upon small amounts of data and tiny computations; we ho...
algorithms and data structures.pdf
producing them. The reasons for animating programs in execution fall into two major categories, which we label checking and exploring. Checking To understand an algorithm well, it is useful to understand it from several distinct points of view. One of them is the static point of view on which correctness proofs a...
algorithms and data structures.pdf
3. Algorithm animation computer interaction. In this use of algorithm animation, the user may be checking his understanding of the algorithm, or may be checking the algorithm's correctness—in principle, he could reason this out, but in practice, it is faster and safer to have the computer animation as a double chec...
algorithms and data structures.pdf
prefer to see an animation over time. Turning to the techniques of animation, computer technology is in the midst of extremely rapid evolution toward ever-higher-quality interactive image generation on powerful graphics workstations (see [RN 91] for a survey of the state of the art). Fortunately, animating a...
algorithms and data structures.pdf
system [Bro 88, BS 85]. A more recent example is the XYZ GeoBench, which animates geometric algorithms [NSDAB 91]. In our experience, the bottleneck of algorithm animation is not the extra code required, but graphic design. What do you want to show, and how do you display it, keeping in mind the limitations of the...
algorithms and data structures.pdf
greatly in getting a feel for the data. 2. Multidimensional data (dimension ≥ 3) can be displayed on a two-dimensional screen using a number of straight forward techniques, such as projections into a subspace, or using color or gray level as a fourth dimension. But our power of perception diminishes rapidly with in...
algorithms and data structures.pdf
In addition to such inherent problems of visual representation, practical difficulties of the most varied type abound. Examples: • Some screens are awfully small, and some data sets are awfully large for display even on the largest screens. • An animation has to run within a narrow speed range. If it is too fast, we ...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License In conclusion, we hold that it is not too difficult to animate simple algorithms as discussed here by interspersing drawing statements into the normal code. Independent of the algorithm to be animated, you can call on your own collection of disp...
algorithms and data structures.pdf
algorithm that constructs half the convex hull (say, the upper half) of a set of points presented incrementally. It accepts one point at a time, which must lie to the right of all preceding ones, and immediately extends the convex hull. The algorithm is explained in detail in “sample problems and algorithms”. progr...
algorithms and data structures.pdf
end; function NextRight: boolean; begin if n ≥ nmax then NextRight := false else begin repeat until Button; while Button do GetMouse(px, py); if px ≤ x[n] then NextRight := false else begin PaintOval(py – r, px – r, py + r, px + r); n := n + 1; x[n] := px; y[n] := py; dx[n] := x[n] – x[n – 1]; { dx > 0 } dy[n]...
algorithms and data structures.pdf
3. Algorithm animation i := b[i]; dx[n] := x[n] – x[i]; dy[n] := y[n] – y[i]; MoveTo(px, py); Line(–dx[n], –dy[n]); b[n] := i end; MoveTo(px, py); PenSize(2, 2); Line(–dx[n], –dy[n]); PenNormal end; procedure Title; begin ShowText; ShowDrawing; { make sure windows lie on top } WriteLn('The convex hull'); WriteLn...
algorithms and data structures.pdf
the reader ideas to try out. We select two standard algorithm animation topics (sorting and random number generation), and an example showing the effect of cumulative rounding errors. Exhibit 3.1: Initial configuration of data, … 27
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 3.1: … and snapshots from two sorting algorithms. Visual test for randomness Our visual system is amazingly powerful at detecting patterns of certain kinds in the midst of noise. Random number generators (RNGs) are intended to simulate "no...
algorithms and data structures.pdf
Exhibit 3.2: One look suffices to unmask a bad RNG. Numerics of chaos, or chaos of numerical computation? The following example shows the effect of rounding errors and precision in linear recurrence relations. The d- step linear recurrence with constant coefficients in the domain of real or complex numbers, Algorithms ...
algorithms and data structures.pdf
3. Algorithm animation is one of the most frequent formulas evaluated in scientific and technical computation (e.g. for the solution of differential equations). By proper choice of the constants c i and of initial values z 0, z 1, … , z d–1 we can generate sequences zk that when plotted in the plane of complex numb...
algorithms and data structures.pdf
have come to associate with fractals—even if the mathematics of generating them is completely different, and linear recurrences computed without error would look much more regular. Notice that the first two images are generated by the same formula, with a single bit of difference in the precision used. The whim of ...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Algorithms and Data Structures 30 A Global Text
algorithms and data structures.pdf
3. Algorithm animation Exhibit 3.3: The effect of rounding errors in linear recurrence relations. Programming projects 1. Use your personal graphics frame program (the programming project of “graphics primitives and environments”) to implement and animate the convex hull algorithm example. 31
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 2. Use your graphics frame program to implement and animate the behavior of recurrence relations as discussed in the section “A gallery of algorithm snapshots”. 3. Extend your graphics frame program with a set of dialog control operat...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Part II: Programming concepts: beyond notation Thoughts on the role of programming notations A programming language is the main interface between a programmer and the physical machine, and a novice programmer will tend to identify "programming" w...
algorithms and data structures.pdf
into an algorithm expressed in sufficient detail to become executable. In keeping with our predilection for graphic communication, the first informal expression of an algorithmic idea is often pictorial. We show by example how such representations, although they may be incomplete, can be turned into programs in a f...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 4. Algorithms and programs as literature: substance and form Learning objectives: • programming in the large versus programming in the small • large flat programs versus small deep programs • programs as literature • fractal pictures: snowflakes a...
algorithms and data structures.pdf
organizational ability. The most important issues to be dealt with include requirements analysis, functional specification, compatibility with other systems, how to break a large program into modules of manageable size, documentation, adaptability to new systems and new requirements, how to organize the...
algorithms and data structures.pdf
considered by itself, it is difficult to understand the entire program, as you need a lot of information to understand how this page relates to the whole. The classic book on programming in the large is [Bro 75]. Programming in the small Small programs, of the kind discussed in this book, challenge our techn...
algorithms and data structures.pdf
difficult, at least initially, since the chain of thought is often subtle. Once you understand it thoroughly, you can reproduce it at any time with much less effort than was first required. Mastery of interesting small programs is the Algorithms and Data Structures 34 A Global Text
algorithms and data structures.pdf
4. Algorithms and programs as literature: substance and form best way to get started in computer science. We encourage the reader to work out all the details of the examples we present. This book is concerned only with programming in the small. This decision determines our choice of topics to be presented, our styl...
algorithms and data structures.pdf
them into the programming language of his choice. In a nut shell, we emphasize substance over form. The purpose of Part II is to help engender a fluency in using different notations. We provide yet other examples of unconventional notations that match the nature of the problem they are intended to describe, and we sh...
algorithms and data structures.pdf
It is instructive to distinguish two types of written materials, and two corresponding types of writing tasks: documents and literature. Documents are constrained by requirements of many kinds, are read when a specific need arises (rarely for pleasure), and their quality is judged by criteria such as formality, co...
algorithms and data structures.pdf
written in software engineering about documentation, a topic whose importance grows with the size and complexity of the system to be documented. We hold that small programs are not documented, they are explained. As such, they are literature, or ought to be. The idea of programs as literature is widely held (see, e...
algorithms and data structures.pdf
idea to specification to algorithm to program. Details of a good program cannot be understood, or at least not appreciated, without an awareness of the grand design that guided the programmer. Whereas details are usually well expressed in some formal notation, grand designs are not. For this reason we renounce form...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License A snowflake Fractal pictures are intuitively characterized by the requirement that any part of the picture, of any size, when sufficiently magnified, looks like the whole picture. Two pieces of information are required to define a specific fract...
algorithms and data structures.pdf
'Snowflake' by the following production rule, which we read as follows: A line segment, as shown on the left-hand side, must be replaced by a polyline, a chain of four shorter segments, as shown at the right-hand side ( Exhibit 4.1). We start with an initial configuration (the zero-generation) consisting of a single...
algorithms and data structures.pdf
theorems about it. Exhibit 4.1: Production for replacing a straight-line segment by a polyline Exhibit 4.2: The simplest initial configuration Exhibit 4.3: The first three generations The production rule drawn above is the essence of this fractal, and of the sequence of pictures that lead up to it. The initial config...
algorithms and data structures.pdf
1. Is our notation sufficiently formal to serve as a program for a computer to draw the family of generations of snowflakes? Certainly not, as we stated certain rules in colloquial language and left others completely unsaid, implying them only by sample drawings. As an example of the latter, consider the question: ...
algorithms and data structures.pdf
4. Algorithms and programs as literature: substance and form segment is to be replaced by a "plain with a mountain in the center", on which side of the segment should the peak point? The drawings above suggest that all peaks stick out on the same side of the curve, the outside. 2. Could our method of description be...
algorithms and data structures.pdf
placement on the screen, some notation could readily be designed to specify every detail with complete rigor. In “Syntax” and “Syntax analysis” we introduce some of the basic techniques for designing and using formal notations. Exhibit 4.4: Refining the description to specify a "left-right" orientation. 3. Should w...
algorithms and data structures.pdf
stop when we have given enough information for an attentive reader to grasp the main idea of each example. Hilbert's space-filling curve Space-filling curves have been an object of mathematical curiosity since the nineteenth century, as they can be used to prove that the cardinality of an interval, co...
algorithms and data structures.pdf
space-filling is quickly seen to be appropriate. Let us illustrate this phenomenon using Hilbert's space-filling curve (David Hilbert, 1862–1943), whose first six approximations are shown in Exhibit 4.5. As the pictures suggest, Hilbert curves are best-described recursively, but the composition rule is more complic...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 4.5: Six generations of the family of Hilbert curves Exhibit 4.6: Productions for painting a square in terms of its quadrants The left-hand side of the first production stands for the task: paint a square of given size, assuming that you e...
algorithms and data structures.pdf
thin strokes), entering and exiting as indicated by the arrows. The right-hand sides of the productions are now easily explained. They say that in order to paint a square you must paint each of its quadrants, in the order indicated. They give explicit instructions on where to enter and exit, Algorithms and Data Str...
algorithms and data structures.pdf
4. Algorithms and programs as literature: substance and form what direction to face, and whether you are painting with your right or left hand. The last detail is to make sure that when the brush exits from one quadrant it gets into the correct state for entering the next. This requires the brush to turn by 90˚, ei...
algorithms and data structures.pdf
invoke the termination rule (e.g. at some fixed depth of recursion), and (2) how to paint the square that invokes the termination rule (e.g. paint it all black). As was the case with snowflakes and with all fractals, the primitive pictures are much less important than the composition rule, so we omit it. The foll...
algorithms and data structures.pdf
program PaintAndWalk; const pi = 3.14159; s = 3; { step size of walk } var turtleHeading: real; { counterclockwise, radians } halfTurn, depth: integer; { recursive depth of painting } procedure TurtleTurn(angle: real); { turn the turtle angle degrees counterclockwise } begin { angle is converted to radian before a...
algorithms and data structures.pdf
Qpaint(level – 1, halfTurn); Walk(–halfTurn); Qpaint(level – 1, halfTurn); Walk(halfTurn); Qpaint(level – 1, –halfTurn) end end; { Qpaint } begin { PaintAndWalk } 39
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License ShowText; ShowDrawing; MoveTo(100, 100); turtleHeading := 0; { initialize turtle state } WriteLn('Enter halfTurn 0 .. 359 (45 for Hilbert curves): '); ReadLn(halfTurn); TurtleTurn(–halfTurn); { init turtle turning angle } Write('Enter depth 1 ...
algorithms and data structures.pdf
conciseness of the two pictorial productions above. The latter state the essentials of the recursive construction, and no more, in a manner that a human can understand "at a glance". We aim our notation to appeal to a human mind, not necessarily to a computer, and choose our notation accordingly. Pascal and its dia...
algorithms and data structures.pdf
The definition above fits Pascal well: In the mainstream of the development of programming languages for a couple of decades, Pascal embodies, in a simple design, some of the most important language features that became commonly accepted in the 1970s. This simplicity, combined with Pascal's preference for language ...
algorithms and data structures.pdf
Lisp, became milestones in the development of programming languages, each in its own way. Whereas COBOL became the most widely used language of the 1960s and 1970s, and Lisp perhaps the most innovative, Algol 60 became the most influential in several respects: it set new standards of rigor for the definition and de...
algorithms and data structures.pdf
language technology and theory, captured the lion's share of attention for several years. Pascal, a much smaller Algorithms and Data Structures 40 A Global Text
algorithms and data structures.pdf
4. Algorithms and programs as literature: substance and form project and language designed by Niklaus Wirth during the 1960s, ended up eclipsing both of these major efforts. Pascal took the best of Algol 60, in streamlined form, and added just one major extension, the then novel type definitions [Hoa 72]. This lig...
algorithms and data structures.pdf
slavishly. Pascal is more than 20 years old, and many of its key ideas are 30 years old. With today's insights into programming languages, many details would probably be chosen differently. Indeed, there are many "dialects" of Pascal, which typically extend the standard defined in 1969 [Wir 71] in different directi...
algorithms and data structures.pdf
the following program fragment, which implements the insertion sort algorithm (see chapter 17 and the section "Simple sorting algorithms that work in time"); –∞ denotes a constant ≤ any key value: A[0] := –∞; for i := 2 to n do begin j := i; while A[j] < A[j – 1] do begin t := A[j]; A[j] := A[j – 1]; A[j – 1] :...
algorithms and data structures.pdf
{ :=: denotes the exchange operator } end; Borrowing heavily from standard mathematical notation, we use conventional mathematical signs to denote operators whose Pascal designation was constrained by the small character sets typical of the early days, such as: ≠ ≤ ≥ ≠ ¬ ∧ ∨ ∈ ∉ ∩ ∪ \ |x| instead of <> <= >= <> not ...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License application) ± Plus-or-minus, used to define an interval [of uncertainty] ∑∏ Sum and product x Ceiling of a real number x (i.e. the smallest integer ≥ x) x Floor of a real number x (i.e. the largest integer ≤ x) √ Square root lo...
algorithms and data structures.pdf
soon as the result is known. In the expression x ∧ y, for example, x is evaluated first. If x evaluates to 'false', the entire expression is 'false' without y ever being evaluated. This convention makes it possible to leave y undefined when x is 'false'. Only if x evaluates to 'true' do we proceed to evaluate y. An...
algorithms and data structures.pdf
function. Example function gcd(u, v: integer): integer; { computes the greatest common divisor (gcd) of u and v } begin if v = 0 then return(u) else return(gcd(v, u mod v)) end; In this example, 'return()' merely replaces the Pascal assignments 'gcd := u' and 'gcd := gcd(v, u mod v)'. The latter in particula...
algorithms and data structures.pdf
4. Algorithms and programs as literature: substance and form routine terminates in one of (at least) two different ways: successfully, by having found the item in question, or unsuccessfully, because of a number of reasons (the item is not present, and some index is about to fall outside the range of a table; we ca...
algorithms and data structures.pdf
if T[a] = x then return(a); { x is already present; return its address } a := (a + 1) mod m { keep searching at the next address } end; { we've found an empty cell; see if there is room for x to be inserted } if n < m – 1 then { n := n + 1; T[a] := x } else err- msg('table is full'); return(a) { return th...
algorithms and data structures.pdf
cover the first two cases that should occur only rarely) and forces all three outcomes to exit the procedure at its textual end. Let us just mention a few other liberties that we may take. Whereas Pascal limits results of functions to certain simple types, we will let them be of any type: in particular, structured ...
algorithms and data structures.pdf
garbage collection and instead provide a procedure 'dispose(…)' for the programmer to explicitly return unneeded cells. If you work with such a version of Pascal and write list-processing programs that use significant amounts of memory, you must insert calls to 'dispose(…)' in appropriate places in your programs. T...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License our understanding slowly grows toward a firm grasp of an idea, supporting intuition is much more important than formality. Thus we describe data structures and algorithms with the help of figures, words, and programs as we see fit in any particu...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 5. Divide-and-conquer and recursion Learning objectives: • The algorithmic principle of divide-and-conquer leads directly to recursive procedures. • Examples: Merge sort, tree traversal. Recursion and iteration. • My friend liked to claim "I'm 2/3...
algorithms and data structures.pdf
is small or large: • If the set D is small, and/or of simple structure, we invoke a simple algorithm A 0 whose application A 0(D) yields R. • If the set D is large, and/or of complex structure, we partition it into smaller subsets D 1, … , D k. For each i, apply A(Di) to yield a result Ri. Combine the results R1, … ...
algorithms and data structures.pdf
R := combine(R1, … , Rk) } end; Notice how an initial data set D spawns set s D1, … , D k which, in turn, spawn children of their own. Thus the collection of all data sets generated by the partitioning scheme is a tree with root D. In order for the recursive procedure A(D) to terminate in all cases, the partitionin...
algorithms and data structures.pdf
5. Divide-and-conquer and recursion "simplicity" that monotonically heads for the predicate 'simple' will do, when algorithm A0 will finish the job. "D is simple" may mean "D has no elements", in which case A 0 may have to do nothing at all; or it may mean "D has exactly one element", and A0 may just mark this elem...
algorithms and data structures.pdf
Suppose that we wish to sort a sequence of names alphabetically, as shown in Exhibit 5.1. We make use of the divide-and-conquer strategy by partitioning a "large" sequence D into two subsequences D 1 and D 2, sorting each subsequence, and then merging them back together into sorted order. This is our algorithm A(D)...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License In the chapter on “sorting and its complexity”, under the section “merging and merge sorts” we turn this divide- and-conquer scheme into a program. Recursively defined trees A tree, more precisely, a rooted, ordered tree, is a data type used primar...
algorithms and data structures.pdf