Sunteți pe pagina 1din 15

Chapter 5: Algorithm divisor of n, r and in particular, the greatest common divisor of n,r.

Therefore step E3
does not change the answer tho the original problem.)
Unit 14: Basic concepts
Question:
[1] The nottion of an algorithm is basic to all of computer programming, so we should
begin with a careful analysis of this concept. 1. How did abacists and algorists compute in the middle age? [2]

[2] The world “algorithm” itself is quite interesting; at first glance it may look as through Ch¬ng 5: ThuËt to¸n
someone intended to write “algorithm” nut jumbled up the first four letters. The word
did not appear in Webster’s New Word Dictionary as late as 1957; We find only the
older form “algorism” with its ancient meaning, i.e the process of doing arithmetic Bµi 14: C¸c kh¸i niÖm c¬ b¶n
using Arabic numerals. In the Middle Ages, abacists computed on the abacus and
algorists computed by algorism. Following the middle ages, the origin of this word was
in doubt, and early linguists attempted to guess at its derivation by making [1]
combinations like algiros [painful] + arithmos [number]; others said no.
[3] Finally, historians of mathematics found the true origin of the word algorism: It comes
from the name of famous Arabic textbook author, “Father of Ja’far, Mohammed, son of
Moses, native of Khow©rizm” Al - Khow©rizm wrote celebrated book “Rule of
restoration and reduction”; other word, “algebra” stems from the title of book,
although the book was not really very algebratic. Gradually the form and meaning of
“algorism” became corrupted. The change from “algorism” to “algorithm” is not hard
to understand in view of the fact that people had forgotten the original derivation of
the word.
[4] By 1950, the word algorthm was most frequently associated with “Euclid’s algorithm,”
a process for finding the greatest common divisor of two numbers which appears in
Euclid’s Elements. It will be instructive to exhibit Euclid’s algorithm here:
Algorithm E (Euclid’s algorithm). Give two positive integers m and n; find their
greatest common divisor, i.e., the largest positive integer that evenly divides both m and
n.

E1. [Find remainder.] Divide m by n, and let r be remainder. (We will have 0 ≤ r ≤ n.)

E2. [It is zero?] If r = 0, the algorithm terminates; n is the answer.

E3. [Interchange.] Set m ← n, n ← r, and go back to step E1.

Of cause, Euclid did not present his algorithm in just this manner.
[5] Each algorithm we consider has been given an identifying letter and the step of the
algorithm is identifying letter followed by a number.
Input. An algorithm has zero or more inputs. I.e., a quantity that is given to it initially
before the algorithm begins. These inputs are taken from specified sets as of objects. In
Algorithm E, for example, there are two inputs, namely m and n, which are both taken
from the set of positive integers.
Output. An algorithm has one or more outputs, i.e., quantities that have a specified
relation to the input. Algorithm E has one output, namely n in step E2, which is the
greatest common divisor of the two inputs. (We can easily prove that this number is
indeed the greatest common divisor, as follows. After step E1, we heve
m = qn + r
for some integer q. If r=0, then m is a multiple of n, and clearly in such a case n is the
greatest common division of m and n. If r<>0, note that any number which divides both
m and r must divide qn + r = m; so the set of divisors of m, n is the same as the set of
Unit 15: Subroutines

[1] When a certain task is to be performed at several different places in a program, it is


usually undesirable to repeat the coding in each place. To avoid this situation, the
2. Where did the word algorithm come from? [3] coding, and (called a “subroutine”) can be put into one place only, and a few extra
3. What is input? instruction can be added to restart the outer program properly after the subroutine is
finished. Transfer of control between subroutines and main programs is called
4. What is output? “subroutine linkage”. Each machine has its own peculiar manner for achieving
efficeent subrouitne linkage, usually involving special instructions. In MIX, the J -
5. What is the greatest common divisor of two positive intergers? [4]
register is used for this purpose.
Exercises:
[2] Subroutines are used to save space in a program; they do not save any time, other
Change Algorithm E (for the sake of efficiency) so that at step E3 we do not than the time implicitly saved by having less space (e.g., less time to load the
interchange values but immediately divide n by r and let m be the remainder. Add program, or fewer passes necessary in the program, or better use of high-speed
appropriate new steps so as to avoid all trivial replacement operations. Write this new memory on machines with several grades of memory). The extra time taken to enter
algorithm in the style of Algorithm E, and call it Algorithm E. (Do it yourselves.) and leave a subroutine is usually negligible. Sobroutines have several other
advantages. They make it easier to visualize the structure of a large and complex
1. Main idea program; they form a logical segmentation of the entire problem, and this usually
Which statement does not express the main idea of the text? Why did you eliminate makes debugging of the program easier. Many subroutines have additional value
the other choices? because they can be used by people other than the programmer of the subroutines.

1. The word algorithm appeared in Webster’s New Word Dictionary in 1957. [3] Most computer installations have built up a large “libraly” of useful subroutines, and
such a library greatly facilitates the programming of standard computer applications,
2. In the Middle Ages, abacitst computed on the abacus and algorist computed by which arise. A programmer should not think of this as the only purpose of subroutines,
algorism. however; subroutines should not always be regarded as "“eneral purpose” programs
to be used by the community. Even the use of very special purpose subroutines,
3. Algorithm is basic to all of computer programming. (*) which are intended to appear in only one program, is an important technique.
2. Understanding the passage [4] The simplest subroutines are those, which we have only one entrence and one exit,
a. Read the [1], [2], [3], [4] and [5] carefully and talk cbout its main idea. such as the MAXIMUN subroutine we have already considered. For reference, we will
recopy that program here, changing it so that s fixed number of cells, 100, is searched
b. Decide whether the following statement are true or false (T/F) by referring to the for the maximun:
information in the text. Then make the neccessary changes so that the false statements
become true. MAX 100 STJ EXIT Subroutine linkage

T/F ENT3 100 M1. Initialize.

1. The word algorithm the title of Al-Khowarizmi’s book. [F] JMP 2F

2. Euclid’s algorithm is finding the greatest common divisor of two numbers. [T] 1H CMPA X, 3 M3. Compare. (1)

3. An algorithm has one or more inputs. [F] JGE *+3

4. These inputs are taken from specified sets of objects. 2H ENT2 0, 3 M4. Change m

5. An algorithm has one output. LDA X, 3 (New maximun found)

6. Outputs are the quantities, which have specified relation to the inputs. DEC3 1 M5. Decrease k.

7. Input and output are actually part of Algorithm. J3P 1B M2. All tested?

3. Understanding words EXIT JMP * Return to main program.

Find synonyms for the following words: In a larger program containing this coding as a subroutine, the single instruction “JMP
MAX100” would cause register A to be set to the current maximum value of location X+1
1. basis 4. (to) jumb up through X+100, and the position of the maximum would appear in rl2. Subroutine linkage
in this case is achieved by the tnstructions “MAX100 STJ EXIT” and, later, “EXIT JMP *”.
2. in doubt 5. (to) intend
Because of the way J - register operates: the exit instruction will then jumpe to the
3. (to) stem 6. (to) consider location following the place where the original reference to MAX100 was made.
[5] It is not hard to obtain quantitative atsterments about the amount of code saved and has an effect just the same as “MOVE A,I (F)” if the letter were admissible. The only
the amount of time loss when subroutines are uesd. Suppose that a piece of coding differences should be the effect on register J and the fact that time to execute the
requires to k locations and that it appears in m places in the program. Rewriting this subroutine will be somewhat longer.
as subroutine, we need an extra instruction in each of the m places where the
subroutine is called. This give total of m + k + 2 locations, rather than mk, so the 1. Main idea
amount saved is Which statement best express the main idea of the text? Why did you eliminate the
(m - 1) (k - 1) - 3 (2) other choices?
1. Transfer of control between the subroutines is called “subroutine linkage”
2. Subroutines are used to save space in a program, but the use of subroutines is an
important technique.
3. Subroutine forms a logical segmentation of the entire problem, and this usually
makes debugging of the program easier.
2. Understanding the passage
a. Read the [1], [2], [3], [4] and carefully and talk about its main idea.
b. Decide whether the following statements are true or false (T/F) by the referring to
the information in the text. Then make the necessary changes so that the false statement
become true.
T/F
1. All the machines have common peculiar manner for achieving afficient subroutine
linkage, usually involving special instructions.

It k is 1 or m is 1 we cannot possibly save any space by using subroutines; this of course, 2. The extra time taken to enter and leave a subroutine is not usually negligible.
is obvious. If k is 2, m must be greater then 4 in order to gian, ect. 3. Most computer installtions have made large library of useful subroutines.
The amount of time lost is the time taken for the extra JMT, STJ, and JMP instructions, 4. Usually, the programmer of the subroutines uses them much more than the other
which are not present if the subroutine is not used; therefore if the subroutine is used t people.
times during a run of the program, 4t extra cycles of time are required.
5. It is not hard to obtain quantitative statement about the amount of code saved and
Question: the amount of time loss when subroutine are used.
1. How can you avoid repeating the coding in each place in a program?
2. What is subroutine?
3. What is subroutine linkage?
4. What is subroutine used for?
5. What are advantages of subroutines?
Exercises:
1. Write a subroutine that generalized MAXN by finding the maximum value of X[1],
X[1+r], X[1+2r], ..., X[n], where r and n are parameters. Give a special entrance for the
case r = 1.
2. Suppose MIX did not have a MOVE operator; Write a subroutine antitled MOVE
such that the calling sequence.
JMP MOVE
NOP A, I (F)
facilities of a computer are usually not learned until after all other features have been
examined, and it frequently happens that only a small fraction of the programmers of
a particular machine ever know much about the details of input and output.
[3] Abrief digression about technology is perhaps apporpriate here. Although
contemporary dictionaries seem to regard the words “input” and “output” only as
nouns, it is now customary to use them grammatically as adjectives and as transitive
verbs. The combined term “input - output” is most frequently referred to by the
abbreviation “I/O”. Inputting is often called reading, and outputting is similarly, called
writing. The stuff that is input or output is generally known as “data” - this word is,
strictly speaking, a plural form of the word “datum”. But it is used collectively as if it
were singular. (E.g., “The date has not been read”.). This completes today’s English
lesson.
[4] Suppose now that we wish to read from magnetic tape. The IN operator of MIX
merely initiates the input process, and the computer continues to execute further
instructions while the input is taking place. Thus the instruction “IN 1000(5)” will be
begin to read 100 words from tape unit number 5 into memory cells 1000-1099, but
the ensuing program must not refer to these memory cells unit later. The input will be
complete only after (a) another I/O operation (IN, OUT or IOC) referring to unit 5 has
been initiated, or (b) the conditional jump instructions JBUS (5) or JRED (5) indicate
that unit 5 is no longer “busy”. The simplest way to read a tape record into locations
1000-1099 and to have the information present is therefore the sequence of two
instructions.
IN 1000 (5)
JBUS * (5) (1)
The method is generally wasteful of computer time, however, because a very large
amount of potentially useful calculating time, say 1000u even 10000u, is consumed by
the repeated execution of the “JBUS” instruction. The program’s running speed can be as
much as doubled if this additional time is utilized for calculation.
[5] One way to avoid this computation time is to have two areas of memory used for the
input; we would read into one area, and while this is going on, the program would
3. Understanding words compute from the data in the other area. For example, suppose the program begins
with the instruction:
Find synonyms for the following words:
IN 2000 (5)Begin reading first record. (2)
1. (to) perform 4. (to) debug
Subsequently, whenever a tape record is desired we may give the following five
2. (to) visualize 5. location commands:
3. (to) arise 6. complex ENT1 1000‘ prepare for MOVE operator.
Unit 16: Input and Output JBUS * (5) ‘ Wait unitl 5 is already
[1] Perhaps the most outstanding differences between one computer and the next are MOVE 2000 (50) ‘ (200-2049) -> (1000-1049) (3)
the facilities available for doing input and output, and the computer instructions,
which govetn these peripheral devices. We cannot hope to discuss in a single book all MOVE 2050 (50) ‘ (2050-2099) -> (1050-1099).
of the problem an techniques that arise in this area, so we will confine ourselves to a IN 2000 (50) ‘ Begin reading next record.
study of typical input-output methods which apply to most computer. The input-output
operators if MIX represent a compromise between the widely varying facilities in
actual machines; to give an example of how to think about input-output, let us discuss
in this section the problem of getting the best MIX input-output.
[2] Many computer users feel that input and output are not actuelly part of “real
programming”, they are merely things that (unfortunately must be done in order to
get information in and out of the machine For this reason, the input and output
In Fig.3 we have added another color of buffer (purple). In this situation, green buffers
represent anticipated input; the program ASSIGNs and green buffer becomes yellow, then
upon RELEASE it turns red and represents a record to be output. The input and output
processes follow around the circle independently as before, except now we turn red
buffers to purple after the output is done, and convenrt purple to green on input. It is
necessary to ensure that none of the pointers NEXTG, NEXTR, NEXTP between ASSIGN
and RELEASE, using the yellow buffer; simultaneously, input is going into thbuffer
indicated by NEXTP; and output is coming from the buffer indicated by NEXTR.
Question:
1. What is the outstanding differences between one computer and the next?
2. Are input and output actually part of “real programming”?
3. Why is not the input and output facilities of a computer learned before?
4. Which operator of MIX merely initiates the process?
5. How can you avoid wasting computation time?
Exercises:
* Show that if a program refers to a single running speed by buffering the I/O, in
favorable circumstances, but it is not possible to improve the running speed over the
amount of time taken by unbuffered I/O by more than a factor of two.
* Generalize the situation of the preceding exercises to the sase when the program
reders to n I/O devices instead of just one.
1. Main idea
Which statement best express the main idea of the text? Why did you eliminate the
other choises?
1. The most outstanding differences between one computer and the next are the
facilities available for doing input and output, and the computer instructions, which
govern these peripheral devices.
2. Only a small fraction of the programmers of a particular machine ever know much
about the details of input and output.
3. One way to avoid this computation time is to have one areas of memory used for
the input.
2. Understanding the passage
a. Read the [1], [2], [3], [4] and [5] carefully and talk about its main idea.
b. Decide whether following statements are true or false (T/F) by the referring to the
information in the text. Then make the necessary changes so that the false statement
NextR becomes true.
NextP R
T/F
P
1. The computer instructions govern these peripheral devices.
These have the same overall effect as (1).
R 2. The input-output operators of MIX represent a compromise between the widely
[6] To conclude this discussion, we will varying facilities in actual machines.
mention a useful method for doing input and
output from the same buffer circle, under certain 3. Useful method for doing input and output is from the same buffer circle, under
G certain conditions.
conditions.
Y Fig.3. Input and output from same circle. 3. Understanding words
G Current
NextG
Find synonyms for the following words:
1. oustading 4. (to) confine
2. facilities 5. (to) compute Unit 17: Linear list
3. (to) govern 6. (to) typical (Stacks, Queue, and Deques)

[1] Usually there is much more structural information present in the data than we
actually want to represent directly in a computer. In each “playing card” node of the
preceding section, for example, we have a NEXT field to specify what card is beneath
in the pile, but there is no direct way to find what card, if any, is above a given card,
or to find which pile a given card is in. Of course there is much information possessed
from the computer representation: the details of the design on the back of the cards,
the relation of the card to other objects in the room, where the game is being played,
the molecules which compose the cards, ect. It is conceivable that such structural
information would be relevant in certain computer application, but obviousty we never
want to store all of the structure present in every situation. Indeed for most card-
playing situations we would not need all of the facts retained in our earlier example;
thus the TAG field which tells whether a card is face up or face down, will often be
unnecessary.
[2] It is therefore clear that we must decide in each case how much structure to
represent in our tables, and how accessible to make each piece information. To make
this decision, we need to know what operations are to be performed on the data. For
each problem we therefore consider not only the data structure but also the class of
operrations to be done on the data; the design of computer representations depends
on the desired function of the data as well as on its intrinsic properties. Such emphasis
on “function” as well as “form” is basic to design problems in general.
[3] In order to illu7strafe this point further, let us consider a simple example which arises
in computer hard design: a computer mamory is often classified as a “random access
memory” i.e., MIX’s main memory; or as a “read only memory”, i.e., one which is to
contail essentially constant information; or a “secondary bulk memory”, like MIX’s disk
units, which connot be accessed at high speed although large quantities of
information can be stored; or an “associative memory,” more properly called a
“content-addressed momory” i.e., one for which information as addressed by values
stored with it rather than by tis location; and so on. Note that the intended function of
each kind of memory is so important that it enters “into the name of the particular
memory type; all of this devices are “memory” units, but the purposes to which they
are put profoundly influence their design and their cost.
[4] A linear list is a set of n 0 nodes X[1], X[2], ... , X[n] whose structural properties
essentially involve only the linear (one-dimensional) relative to positions of the nodes:
the facts that, if n > 0, X[1] is the first node; when 1 < k < n, the kth node X[k] is
precceded by node X[ k - 1] and followed by X[ k + 1]l and X[n] is the last node.
[5] The operations we might want to perform on linear lists, include, for example, the
following.
i) Gain access to the kth node of the list to examine and/or change the contents of
its fields.
ii) Insert a new node just before the kth node.
iii) Delete the kth node.
iv) Combine two or more linear lists into a single list.
v) Split a linear list into two or more lists.
vi) Make a copy of a linear list.
vii) Determine the number of nodes in a list.
viii) Sort the nodes of the list into ascending order based on certain fields of the
nodes.
ix) Search the list for the occurrence of the node with a particular value in some
field.
In operation (i), (ii) and (iii), the special case k = 1 and k = n are not principal
importance since the first and the last items of a linear list may be easier to get at than a
general element is.
A computer application rarely calls for all nine of above opereaent linear lists
depending on the class of operations which are to be done most frequently. It appears to
be impossible to design a single representation method for linear lists in which all of
these operations are efficient; for example, the ability to gain access to the kth node of a
long list for random k is comparatively hard to do if at the same time we are inserting and
deleting items in the middle of the list. Therefore we distinguish between type linear lists
depending on the principal operations to be performed, just as we have noted that
computer memories are distinguished by their intended applications.
[6] Linear lists in which insertions, deletions, and accesses to values occur almost always
at the first or the last node are very frequently encountered and we give them special
names:
A stack is a linear list for which all insertions and deletions (and usually all accesses)
are made at one end of the list.
A queue is a linear list for which all insertions are made at one end of the list; all
deletions (and usually all accesses) are made at the other end.
A deque (“double-ended queue”) is a linear list for which all insertions and deletions
(and usually all accesses) are made at the ends of the list.
OUTPUT FROM STACK INPUT TO STACK A deque is therefore more
general than a stack or a queue; it
has some properties in common
with a deck of cards. We also
distinguish output-restricted or
input- restricted deques, in which
deletions or insertions,
respectively, are allowed to take
place at only one end.
Fig.1 A stack represented as railway switching network.
THIS TRACK CLOSED ON INPUT-RESTRICTED DEQUE Fig.2 A deque
represented as a railway
switching network.
OUTPUT DEQUE INPUT Question:
1. How can represent
FROM DEQUE TO DEQUE structural information?
2. How many types of
computer memory are
THIS TRACK CLOSED ON OUTPUT-RESTRICTED DEQUE there?
3. Why is the intended function of each kind important? 3. A stack is a linear list for which all insertions and deletions (and usually all
accesses) are made at the ends of the list.
4. How many operations on linear lists do you know? What are they?
4. A queue is a linear list for which all insertions are made at one end of the list; all
5. What is a stack? deletions (and usually all accesses) are made at the other end.
6. What is a queue? 5. A deque is linear list for which all insertions and deletions (and usually all accesses)
7. What is a deque? are made at one end of the list.

Exercises: 6. A stack is therefore more general than a deque or a queue.

* 1) An input restricted deque is linear list in which items may be inserted at the one 3. Understanding words
end but removed from either end; clearly an input-restricted deque can operate either as Find synonyms for the following words:
a stack or as a queue, if we consistently remove all items from one of the two ends. Can
an output-restricted deque also be operated either as a stack or queue? 1. present 4. (to) desire 7. essentially
* 2) Imagine four railroad cars positioned on the input side of the stack in Fig.1, 2. relevant 5. (to) gain 8. property
numbered 1, 2, 3 and 4, respecyively. Suppose we perporm the following sequence of
perations (which is compatible with the direction of the arrows in the diagram and does 3. accessible 6. (to) split
not repuire cars to “jump over” other cars): (a) move car 1 into the stack; (b) move car 2 Unit 18: Trees
into the stack (c) move car 2 into the output; (d) move car 3 into the stack; (e) move car
4 into the stack; (f) move car 4 into the output; (g) move car 3 into the output; (h) move
car 1 into the output.
[1] Now we turn to a study of trees, the most important nonlinear structures arising in
As a result of these operations the original order of the cars, 1234, has been changed computer algorihms. Generally speaking, tree structure means a “branching”
into 2431. It is the purpose of this exercise to examine what permutations are obtainable relationship between nodes, much like that found in the tree of nature.
in such a manner from stacks, queues or deque.
[2] Let us define a tree formally as finete set T of one or more nodes such that:
If there are six railroad cars numbered 123456, can they be permuted into the order
a) There is one specially desgnated node called the root of the tree, root (T); and
325641? Can they be permuted into the order 154623? (In case it is possible, show how
to do it.) b) The remaining nodes (excluding the root) are partitioned into m ≥ 0 disjoint sets
1. Main idea T1, ... , Tm, and each of these sets in furn is a tree. The trees T1, ..., Tm are called the
subtrees of the root.
Which statement best expresses the main idea of the text? Why did you eliminate the
other choices? [3] The definition just given is recursive, i.e., we have defined a tree in terms of trees. Of
course, there is no problem of circularity involved here, since trees with one node
1. It is therefore clear that we must not decide in each case how much structure to must consist of only the root, and tree with n > 1 nodes are defined in terms of trees
represent in our tables, and how accessible to make each piece information. with less than n nodes; hence the concept of a tree with two nodes, three nodes, or
2. A stack is linear list for which all insertions and deletions (and usually all accesses) ultimately any number of nodes, is determined by the definition given. There are
are made at one end of the list. nonrecursive ways to define trees, but a recursive definition seems most approriate
since recursion is an innate characteristic of tree structures. The recursive character of
3. Therefore we distinguish between type linear lists depending on the principal trees is present also in nature, since buds on young trees eventually grow into
operations to be performed, just as we heve noted that computer memories-are subtrees with buds of their own, etc. It is easy to give rigorous proofs of important
distinguished by their intended applications. facts about tree based on a recursivedefinition such as the one above, by using
induction on the number of nodes in a tree;
2. Understanding the passage
a. Read the [1], [2], [3], [4], [5] and [6] carefully and talk about its main idea.
b. Decide whether the following statements are true or false (T/F) by referring to the
information in the text. Then make the necessary changes so that the false statements
become true.
T/F
1. Usually there is much more structural information present in a computer than we
actually want to represent directly in the data.
2. Computer application rarely calls for all nine of above operations in their full
generality.
[7] There are many ways to draw diagrams of trees. Besides the diagram of Fig.5, three
B A B of principal alternative are shown in Fig.7, depending where the rootis placed. It is not
[4] It is follows from our frivolous joke to worry about how a tree structure is drown in diagrams, since there
A definition that every node of are many occasions in which we would like to say one node is “above” or “higher
A B C than” another node, or to refer to the “rightmost” element, etc. Certain algorithms for
a tree is root of some
D dealing with tree structures have become know as “top down” methods, as opposed
D subtrees contained in the
whole tree. The number of to “bottom up”. This terminology leads to confusion unless we adhere to a uniform
D C
subtrees of a node is called convention for drawing trees.
C F
E E E the degree of that node. A It may seem that the form of Fig.5 would be preferable simply because that is how
node of degree zero is called trees grow in nature;
F a terminal node or some
F G G G times a “leaf”. A Question:
nonterminal node is often
1. What does mean tree structure?
called a branch node. The
(a) (b) (c)
level of a node with respect 2. What definition is seemed most appropriate? Why?
to T is defined by saying
that the root has level 1, 3. How could rigorous proofs of important facts about tree be given based on a
Level 4 G G recursive definition?
and other nodes have a
D level that is one higher than 4. What is a degree of a node?
Level 3 F F they have with respect to
E the subtree of the root, Tj, 5. What is a terminal node?
E which contains them.
6. What is a forest?
D C These [5] concepts are
Level 2 C illustrated in Fig.5, which 7. How can you draw diagrams of trees?
shows a tree with seven Exercises:
B B nodes. The root is A, and it
has the two subtrees {B} 1. How many different trees are there with three nodes: A, B and C?
Levle 1 A A
and {C, D, E, F, G}. The tree
2. How many different oriented trees are there with three nodes: A, B, and C?
{C, D, E, F, G} has node C as
Fig.5. A tree Fig.6. Another tree
its root. Node C is on level 2 1. Main idea
with respect to the whole tree, and is has three subtrees {D}, {E} and {F, G};
Which statement best expresses the main idea of the text? Why did you eliminate the
Therefore C has degree 3. The terminal nodes in Fig.5 are B, D,E and G; F is only node other choices?
withdegree 1. G is only node with level 4.
1. The study of tree is the most important nonlinear structure arising in computer
If the relative order of the subtrees T1, ..., Tm in (b) of the definition is important, we algorithms.
say the tree is an ordered tree; when m ≥ 2 in an ordered tree, it makes sense to cal T2
2. Rigorous proofs of important facts about tree based on a recursive definition by
the “second subtree” of the root, etc. If we do not care to regard two trees as different using induction on number of nodes in a tree.
when they differ only in the respective ordering of subtree of nodes, the tree is said to be
oriented, since only the relative orientation of the nodes, not their order, is being 3. Drawing a tree structure is not a problem.
considered. The very nature of computer representation defines an implicit ordering for
nay tree, so in most cases ordered trees are of greatest interest to us. We will therefore 2. Understanding the passage
tacitly assume that all trees we discuss are ordered, unless it is explicitly started a. Read the [1], [2], [3], [4] and [5] carefully and talk about its main idea.
otherwise. Accordingly, the trees of Fig.5 and Fig.6 will generally be considered to be
different, although they would be the same as oriented trees. b. Decide whether the following statements are true or false (T/F) by referring to the
information in the text. Then make the necessary changes so that the false statments
[6] A forest is a set (usually an ordered set) of zero or more disjoint trees. Another way to become true.
phrase part (b) of the definition of tree would beto say that thenodes of a tree
excluding the root form a forest.
There is very tittle distinction between abstract forests and trees; If we delete the root
of tree, we have a forest, and conversely, if we and just one node to any forest we get a
tree. Therefore the words tree and forest are often used almost interchangeably during
informal discussions about tree structures. T/F
1. Tree structure means a “branching” relationship between nodes, much like that arise in applications are themselves inherently binary, so binary trees are of interest in
found in the tree of nature. their own right.
2. Tree is a set of nodes. [3] There are many algorithms for manipulation of tree structures, and one idea that
occurs repeatedly in these Algorithms is the notion of traversing or “walking through”
3. Nonrecursive ways to define trees are more appropriate than recursive. a tree. This is a method of examining the nodes of the tree systematically so that
4. A forest is a set (usually an ordered set) of zero or more disjoint trees. each node is visited exactly once. A computer traversal of the tree gives us a linear
arrangement of the node, and many algorithms are facilitated if we can talk about the
5. The words tree and forest are not used interchangeably during informal discussions “next” node following or precceding a given node in such a sequence.
about tree structures.
[4] Three principal ways may be used to traverse a binary tree: we can visit the node in
6. There is only one way to draw diagrams of trees. It is “top down” method. preorder, postorder, or endorder. These three methods are defined recursively; when
the binary tree is empty, it is “traversed” by doing nothing., and otherwise the
3. Understanding words
traversal proceeds in three steps:
1. disjoint 4. whole
Preorder traversal Postorder traversal Endorder traversal
2. recursive 5. implicit
Visit the root Traverse the left subtree Traverse the left subtree
3. finite 6. to be oriented
Traverse the left subtree Visit the root Traverse the right subtree
Unit 19: Traversing binary trees
Traverse the right subtree Traverse the right subtree Visit the root

[1] It is important acquire a good understanding of the properties of binary trees before
making further investigations of trees, since general trees are usually represented in
terms of some equivalent binary tree inside a computer.
[2] We have defined a binary tree
(1) A as a finite set of nodes that
either is empty, or consists of a
C root together with two binary
B F trees. This definition suggests a
J natural way to represent binary If we apply these definitions to the binary tree (2), we find that the nodes in preorder
E tree within a computer: We are
D H may have two links. LLINK and
RLINK, within each node, and a A B C D E G F H J (3)
link variable T which is a “poiter (First comes the root A, then comes the left subtree.)
G to the tree”. If the tree is
empty, T = A; otherwise T is the in preorder, and finally comes the right subtree in preorder.) In postorder we
address of the root of the tree, B visit the root between visits to the nodes of each subtree, essentially as
and LLINK (T), RLINK (T) are pointers to the left and right, respectively, subtrees of the through the nodes were “projected” down into a single line, and this gives
root. These rules recursively define the memory representation of any binary tree; for the order
example, (1) is presented by (2)
D B A E G C H F J (4)
T This simple and D
The endorder for the nodes of this binary tree is, similarly,
natural memory
representation accounts D B G E H J F C A
A for the special
(2) importance of binary tree [5] We will see that these ways of arranging the nodes of a binary tree into a sequence
structures. Besides the are extremely important, as they are intimately connected with most of the computer
B C fact that general trees method dealing with trees. (Note: The names preorder anf postorder come from the
are convenienfly fact that each root is visited before or after its left subtree; this terminology is
representable as binary motivated by the special significance given to left subtrees when binary trees are
D E F trees, many trees that used to represent general trees. In many applications of binary trees, there ia more
symmetric between the meanings of left subtrees anf right subtrees, and in such
cases the term symmetric order is used as a synonym for postorder. Clearly postorder,
which puts the root in the middle, is essentially symmetric between left and right: if
G H J the tree is reflected about a vertical axis, the symmetric order is simply reversed).
[6] A recursively started definition such as the one just given for the tree basic orders, 1. Main idea
must be reworked (in order to make it directly applicable to computer
implementation. We usually make use of an auxiliary stack, as in the following Which statement best expresses the main idea of the text? Why did you climinate the
algorithm: other choices?

[7] Algorithm T (Traverse binary postorder). Let T be pointer to a binary tree having a 1. We have defined a binary tree as a finite set of nodes that neither is empty, or
representation as in (2); this algorithm visits all the nodes of the binary tree in consists of a root together with two binary trees.
postorder, making use of an auxiliary stack A: 2. This is a method of examining the nodes of the tree systematically so that each
T1. [Initialize.] Set stack A empty, and set the link variable P <- T. node is visited exactly once.

T2. [P = A?] If P = A, go to 3. We will see that these three ways of arranginf the nodes of a binary tree into a
step 4. sequence are extremely important, as they are intimately connected with most of the
N computer method dealing with trees.
T1. Initialize T2. P=A? T3.Stack <=P T3. [Stack <= P.] (Now P
points to a nonempty binary tree 2. Understanding the passage
O
which is to be traversed.) Set A a. Read the [1], [2], ... and [8] carefully and talk about its main idea.
<= P, i.e., push the value of P
Y es onto stack A. b. Decide whether the following statement are true or false (T/F) by referring to the
P <- RLINK(P) information in the text. Then make the necessary changes so thatthe false statements
Then set P <- LLINK (P) enf become true.
T4.P <=Stack T5.Visit P return to step T2.
T/F
T4. [P <= Stack.] If stack A is
Empty empty, the algorithm terminates; 1. The method traversing binary trees was defined recursively.
ortherwise set P <= A.
2. Besides the fact that general trees are conveniently representable as binary trees,
T5. [Visit P.] “Visit” NODE (P) (se below.) Then set p <- RLINK (P) and turn to step 2. many trees that arise in applications are themselves inherently binary, so binary trees
areinterest in their own.
[8] In the final step of this algorithm, the word “visit” means we do whatever activity is
intended as the tree is being traversed. Algorithm T runs like a coroutine with respect 3. These are many ways of arranging the nodes of a binary tree into asequence.
to this other activity: the main program activates this coroutine whenever it wants P
4. The traversal of the tree is based on a linear arrangement of the nodes.
to move from one node to it postorder successor. Of coure, since this coroutine calls
the main routine in only one place, it is not much different froma subroutin. Algorithm 5. Three principalways may be used to traverse a binary tree: we can visit the node
T assumes that the external activity deletes neither NOD(P) nor any of it ancestors in preorder, postorder, or endorder.
from the tree.
6. The word “visit” means wedo whatever activity is intended as the tree is being
Question: traversed.
1. How can a binary tree be defined? 3. Understanding words
2. What is the main property of the traversing binary tree? Findsynonyms for the followingwords:
3. What are there three principal ways to be used to traverse a binary tree? 1. arrange 4. (to) facilitate
4. How many steps does the traversal proceed in? 2. reverse 5. (to) precede
5. Is the method important? Where is it used? 3. otherwise 6. (to) terminate
Exercises:
1. The text defines three basic orders for traversing binnary tree; another alternative
would to be proceed in tree steps as follows:
a. Visit the root,
b. Traverse the right subtree,
c. Traverse the left subtree,
using the same rule recursively on all nonempty subtrees. Does this new order bear
any simple relation to the three orders already discussed?
Chapter 6: The basic of networking
address on the network and is known as a node or work-station. The network support
software in each workstation typical occurs in layers. The leyer at the lowest level
Unit 20: Local Area Networks talks directly to the network adapter card; the layer at the highest level talk to your
application program anf provides a programmatic interface that your application
program and provides a programmatic interface that your application can use to
[1] The “Year of the LANs” never really happened; local erea networks just sort of crept access the network. Each layer implements a well-defined method of communicating
up on us and invaded our offices. This invasion shows no signs of slowing LANs are across the network. (protocol).
here to stay. What happens now that your personal computer is tied to your
neighnour’s computer with telephone wire, or with a thick cable that looks like it could Now that you know what a LAN is, let’s see how a LAN provides PC-to-PC
easily carry 110 volts? Should you use the LAN just to share disk space or printer? communication and how it lets you access a file server’s hard driver.
Does your company plan to develop applications that share files on the LAN - Message Packets (Frames)
application that a year or two ago would have been targeted for the big, expensive
mainframe computer? What can you do with LANs that you can not do with [6] At the lowest level, networked PCs communicate with one other and with the file
mainframes? Do you always have to use a file server, or can your uesr communicate server using message, ogten called frames. The foundation on which all LAN activity is
PC - to PC as peers? What system design, coding, and debugging skills do you need to based, these frames are sent and received by the network adapter and its support
take advantage of a LAN? Forward - looking data processing deparments now are software. The network support software sends frames for many purposes, including
developing significant (mission-critical) system for LANs. Other systems, in other the fllowing:
companies, soon will follow. These systems are costeffective, bring the application
close to the user, take advantage of the PCs excellent capability of interacting with * Open a communications session with another adapter.
user and distribute the work load across several computers. * Send data (perhaps a record from a file) to a PC.
LANS-A NEW FRONTIER * Acknowledge the receipt of data frame.
[2] Local area networks are a new frotierin software technology. If you are accustomed to * Broadcast a message to all other adapters.
working with mainframe computers you will like the way that a LAN gets you closer to
your application’s users through the screen and keyboard control afforded by personal * Close a communication session.
computers. The file and record-looking tools seem rudimentary, but you will frow used
[6] PC-to-PC communications are easy to visualize in this ways: you programmatically ask
to them. After having work withtools such as CICS, yourwill find the facilities for
a protocol such as NETBIOS or IPX to send or receive a message, and the higher-level
communicating information among users. On the other hand, if you have devoloped
protocol works with the adapter support soft ware to send and receive the appropriate
PC applications before, you have been in a single-user environment, you must adjust
data frames and acknowledgement frames. Different types of frames serve different
your thinking toaccount for the added dimension of having multiple concurrent users
purposes. For example, some of the frames used in implementations of NETBIOS are
of your software. You will like the new facilities for user-to-user comminications.
Name Query frames, session Request frames, data frames, and close frames.
[3] A medium-sized LAN represents collectively, more raw computinghorsepowerthan a
[7] Different networks’ implementations define frames indifferent ways, but the following
mainframe. You say: “This fellowismistakenPCs will never stack up to amainframe” If
data items are common to all implementaions.
that is yourreaction, you are thinking of PCs in term of individual users working at
individual PCs running individual off-the-shelf applications (word processors or * The sender’s network address.
spreadsheets, most likely). Until now, this sort ofindividual usage has been a classic
way to treat PCs. But think of 50 personal computers on a LAN being used by 40 * The destination network address.
people. Forty workstations are used as datacollection andinquiry vehicles, and 10 of * An identination of the contents of the frame.
the computers, unattended, run programs that perform the calculations, update the
database and work in close harmony with the software on the interactive * A data record or message.
workstations. These 10 “engines” are fast 80386 or 80486 computer with a total rating
about 60 MIPS. Each has a 300-megabyte hard disk with a 10-millionsecond average * A checksum or CRC for error-detection purposes.
access time.Each”engine” communicates with the other computers on the LAN at16 How are frames used in the context of sharing files on a file server? What happens
megabits per second. when an application running on a workstation wanrs to open a file that resides on the file
CHARACTERISTICS server? The answer lies on the redirection of DOS function calls.

[4] A local erea network is a group of PCs that communicate with each other by message Here is an ordinaty program statement (in Turbo C) that opens a file:
packets, with each packet containing sender and receiver address information for Char filename [ ] = “DATABASE-FIL ...”;
routing purpose. A LAN always has one or more file servers. Most of the processing
occurs on the local PC. not on the file server. Furthermore, in the LAN can share files, Nit file_handle;
lock record, obtain its unipue workstation name, and send messages to other
File_handle = open (filename, O_RDWR O O_DENYNONE);
computers.
Question:
[5] Less formally, a LAN is a group of PCs connected to one another by cables. Each PC
contains a network adapter card and network support software. Each PC has a unipue 1. Is LAN developing at high speed? What shows that?
2. What does LAN bring to the users? b. Decide whether the following statements are true or false (T/F) by referring to the
information in the text. Then make the neccessary changes so that the false statements
3. Why is it said that, LAN is a new Frontier? become true.
4. What is the difference between LAN and Mainframe? T/F
5. Do you think that LAN is much more powerful than a mainframe? 1. Local area network trail on us and storm inour offices.
6. What are the characteristics of LANs? 2. What can you do with LANs that you can do with mainframes.
7. What can a PC do in the LAN environment? 3. LAN’s systems are not cost-effective.
4. Local area networks are a new field of learning in software technology.
5. A medium-sized LAN represents individually, more raw computing horsepower than
a mainframe.
6. A local area network is a group of PCs that inform each other by message packets,
with each packet containing sender and receiver address information for routing purpose.
7. Most of the processing occurs on the file server not on the local PC.
8. In the LAN environment, a PC can share files, lock record, obtain its unique
workstation name, and send messages to other computers.
9. The network support software in each workstation typically occurs in layers.
10. Different networks’ implementations define frames in common ways, and the
following data items aredifferent to all implementations.
3. Understanding words
Find synonyms for the fllowing words:
1. afford 5. run
2. stack up 6. perform
8. How does the PC connect to each other?
3. off-the-shelf application 7. communicate
9. What’s main condition for connection of PC to PC?
4. run out
10. Where does the network Support Software occur?
11. What are the functions of network adapter and its support software?
12. What is the purpose of sending of frames of network support software?
Exercises:
1. Mainidea
Which statement best expresses the main idea of the text? Why did you climinate the
other choices?
1. Local area networks are new field of learning in software technology.
2. A LAN gets you closer to your application’s users through the screen and keyboard
control afforded by personal computers, with each other by message packets.
3. Different types of frames serve different purposes.
2. Understanding the passage
a. Read the [1], ..., [7] carefully and talk about its main idea.
destination, which acknowledges its reception. On receiving an acknowledgement
frame containing its own network address, the sending station relinquishes the
network by recirculating a token.
Unit 21: Types of networks Unless an adapter card malfunctions and goes out of turn (without waiting for the
token), collisions never occur on token-passing network.

[1] LANs come in two basic flavors collision-sensing and token-passing. Ethernet is an Components of a LAN.
example of a collision-sensing network, and Token Ring is an example of a token- [5] Basic hardware components consist of network adapter cards, cable, and either
passing network. In the collision-sensing environment, often referred to with the access untils or repeaters. Depending on tis type and complexity, your network may
abbreviation CSMACD (Carrier Sense, Multiple Access with Collision Detection) a also include bridges. routers, concentrators, hubs, ... and transceivers. You don’t need
network adapter card with a frame to send fast listens to the network to see if it is to understand these items to conceptualize a LAN for programming. One other
quiet. If the adapter card hears another card sending a frame at that moment, it wants component-the file server.
a microsecord or so and tries again. Even with approach, collisions (two workstations
attempting to transmit at exactly the same moment) can and do happen, CSMACD Questions
networks are designed to expect collisions and handle them by retransmitting frames
when necessary. These retransmission are handled automatically by the adapter card 1. What are the basic characteristic of LAN?
and are transparent to the user. Although poor CSMACD network performance is often 2. What does the adapter card with a main frame do in the collision-sensing
mistakenly blamed on the number of users simultaneously sending or receiving environment?
message traffic on the network more the 90 percent of transmission problems on the
Ethernet work are actually caused by faulty cable or malfunctioning adapter cards. 3. What does ‘collision’ mean?
[2]
On an Ethernet 4. What are the functions of CSMACD?
An Ethernet network network data is
5. What happen when CSMACD is poor?
broadcast
throughout the 6. How is an Ethernet network data broadcast?
Workstaton Workstaton File server Workstaton network in all
directions at the 7. How is a Token-passing network viewed?
rate of 10 megabits 8. How does data (frame) move in a Token-passing network?
per second. Each
Coaxial cable 10 megabittes per second workstation receives 9. What is a Token?
Fig.1 every frame but
only those 10. How does a process of a sending a frame occur?
workstation meant to receive a frame (as specified in the frame’s destination network 11. How does a process of receiving a frame occur?
address) respond with an acknowledgement (Fig.1)
Exercises
[3] A Token-passing network, on the other hand, can logically be viewed as a ring. This is
true even through the network can be wired electrically as a star, bacause data 1. Main idea
(frames) move around the network from workstation to workstation (Fig.2). Each
Which statement best expresses the main idea of the text? Why did you climinate the
network adapter card regenerates the signal from its “upstream” neighbor and passes
other choices?
the result a long to the next workstation.
1. Collision-sensing and token-passing are primary characteristics of a LAN.
[4] A token is special type of frame.
Fig.2
It contains no message data, but 2. On an Ethernet network data is broadcast throughout the network in all directions.
A Token Ring network
is circulated continuously around
the ring idle periods. When it 3. A Token contains no message data, but is circulated continuously around the ring
wants to send a frame, the idle periods.
Workstation Workstation
workstation waits for the token 2. Understanding the passage
and if the token is free (no other
workstation is transmitting at the a. Read the [1], ..., [5] carefully and talk about its main idea.
Msau moment) the adapter card marks
the frame “in use” and transmits b. Decide whether the following statements are true or false (T/F) by referring to the
the frame to the next information in the text. Then make the neccessary changes so that the false statements
downstream workstation. The become true.
stream is passed along from T/F
Workstation Workstation adapter to adapter until it
eventually reaches its
1. In the collision-sensing environment, a network adapter card with a frame to 2. approach 5. recerse
receive fast listens from the network to see if it is quiet.
3. respond
2. On receiving a acknowledgement frame containing its own network address, the
sending station relinquishes the network by recirculating a token.
3. Each workstaton receives every frame but only those workstations meant to Unit 22: Network adapter cards
receive a frame respond with an acknowledgement. As mentioned before, network adapter cards can be either collision-sensing or token-
4. A Token-passing network can logically be viewed as a ring. passing. Both kinks of adapters contain sufficient onboard logic to know when it is okay to
send a frame and to recognize when the frame they receive are intended for them. Along
5. A token contains message data. with the adapter support software, both types of cards perform seven major steps during
the process of sending or receiving a frame. When data in being sent, the following steps
6. A token can send a frame at any time. are performed in the order whown: When data is being received, however the steps are
reversed:
1. Data transfer. Data is transferred from PC memory to the adapter card or from the
adapter card to PC memory by DMA shared memory or programmed IO.
2. Buffering. While being processed by the network adapter card, data is held in a
buffer. The buffer gives the card access to an entire frame at one and lets the card
manager the differnce between the data rate of the network and the rate at which
the PC can process data.
3. Frame formation. The network adapter has to break up the data (or on raception,
reassemble it) into managerable chunks. On an Ethernet network, these chunks are
kilobytes at least one network uses 12 kilobytes. A frame header is prefixed to the
data packet, a frame trailer is suffixed to it. At this point a complete ready-for-
transmitssion frame has been created. (On reception the header and trailer are
removed at this stage.)
4. Cable access. In a CSMACD network such as Ethernet, the network adapter ensures
that the line is puite sending its data. In a token-passing network, the adapter waits
until it dets a token that it can grab and claim. (Cable access is irrelevant to
message reception.)
5. Parallel and serial conversion. The bytes of data in the buffer are sent or received
through the cable in serial fashion with one bit following the next. The adapter
card makes this conversion on the split second before transmission (or after
reception).
6.
7.

7. Collisions always occur on token-passing network.


3. Understanding works
Find synonyms for the following works:
1. flavor 4. relinquish

S-ar putea să vă placă și