text
stringlengths
1
1k
source
stringclasses
12 values
that each node has either exactly, or at most, two children. The pictorial grammar shown in Exhibit 5.2 captures this recursive definition of 'binary tree' and fixes the details left unspecified by the verbal description above. It uses an alphabet of three symbols: the nonterminal 'tree symbol', which is also the...
algorithms and data structures.pdf
We may make the production rules more detailed by explicitly naming the coordinates associated with each symbol. On a display device such as a computer screen, the x- and y-values of a point are typically Cartesian coordinates with the origin in the upper-left corner. The x-values increase toward the bottom and the...
algorithms and data structures.pdf
5. Divide-and-conquer and recursion Exhibit 5.5: Adding coordinate information to productions in order to control graphic layout The translation of these two rules into high-level code is now plain: procedure p1(x, y: coordinate); begin eraseTreeSymbol(x, y); drawLeafSymbol(x, y) end; procedure p2(x, y: coordinate; d: ...
algorithms and data structures.pdf
children: A child may be a node or a leaf. This lets us subsume two frequently occurring classes of binary trees under one common definition. 1. 0-2 (binary) trees. We may identify leaves and nodes, making no distinction between them (replace the squares by circles in Exhibit 5.3 and Exhibit 5.4). Every node in th...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Recursive tree traversal Recursion is a powerful tool for programming divide-and-conquer algorithms in a straightforward manner. In particular, when the data to be processed is defined recursively, a recursive processing algorithm that mirrors the...
algorithms and data structures.pdf
Recursive tree traversals use divide-and-conquer to decompose a tree into its subtrees: At each node visited along the way, the two subtrees L and R to the left and right of this node must be traversed. There are three natural ways to sequence the node visit and the subtree traversals: 1. node; L; R { preorder, or...
algorithms and data structures.pdf
becomes slightly simpler: if not empty(T) then { … } To accomplish the k-th traversal scheme (k = 1, 2, 3), 'visit k' performs the desired operation on the node, while the other two visits do nothing. If all three visits print out the name of the node, we obtain a sequence of node names called 'triple tree t...
algorithms and data structures.pdf
5. Divide-and-conquer and recursion Exhibit 5.7: Three standard orders merged into a triple tree traversal Recursion versus iteration: the Tower of Hanoi The "Tower of Hanoi" is a stack of n disks of different sizes, held in place by a tall peg (Exhibit 5.8). The task is to transfer the tower from source peg S to a ta...
algorithms and data structures.pdf
2. Move the largest disk to the target peg T. 3. Transfer D' on top of the largest disk at the target peg T. Exhibit 5.8: Initial configuration of the Tower of Hanoi. Step 1 deserves more explanation. How do we transfer the n – 1 topmost disks from one peg to another? Notice that they themselves constitute a tow...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License The following procedure is an equally elegant and more efficient iterative solution to this problem. It assumes that the pegs are cyclically ordered, and the target peg where the disks will first come to rest depends on this order and on the par...
algorithms and data structures.pdf
Chapter 4 presented some beautiful examples of recursive pictures, which would be hard to program without recursion. But for simple recursive pictures iteration is just as natural. Specify a convenient set of graphics primitives and use them to write an iterative procedure to draw Exhibit ...
algorithms and data structures.pdf
5. Divide-and-conquer and recursion procedure citr(x, y, r: real; d: integer); var vr: real; { variable radius } i: integer; begin vr := r; for i := 1 to d do { equitr(x, y, vr); vr := vr/2; circle(x, y, vr) } { show that the radius of consecutively nested circles gets exactly halved at each step } end; The flag o...
algorithms and data structures.pdf
of Alfanumerica (RSA). Both nations fly the same flag but use entirely different production algorithms. 1. Write a procedure ISA(k: integer); to print the ISA flag, using an iterative algorithm, of course. Assume that k is a power of 2 and k ≤ (half the line length of the printer). 2. Explain why the printer industr...
algorithms and data structures.pdf
and RSA, a growing number of flags can be seen fluttering in the breeze turned around by 90˚. Exercises 1. Whereas divide-and-conquer algorithms usually attempt to divide the data in equal halves, the recursive Tower of Hanoi procedure presented in the section 'Recursion versus iteration: The Tower of Hanoi...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 6. Syntax Learning objectives: • syntax and semantics • syntax diagrams and EBNF describe context-free grammars • terminal and nonterminal symbols • productions • definition of EBNF by itself • parse tree • grammars must avoid ambiguities • inf...
algorithms and data structures.pdf
draws the child" are both syntactically correct according to the accepted rules of grammar. The first sentence clearly makes sense, whereas the second sentence is baffling: perhaps senseless (if "draw" means "drawing a picture"), perhaps meaningful (if "draw" means "pull"). Semantic aspects—whether a sentence is me...
algorithms and data structures.pdf
into pseudo-English has deliberately been built into COBOL; for example, "compute velocity times time giving distance" is nothing but syntactic sugar for "distance := velocity · time". Much more important is the distinction that natural languages are not rigorously defined (neither the vocabulary, nor the syntax, a...
algorithms and data structures.pdf
defined formally. However, system-dependent differences are not always described precisely. The compiler often determines in detail the syntactic correctness of a program with respect to a certain system (computer and operating system). The semantics of a programming language could also be defined fo...
algorithms and data structures.pdf
6. Syntax The syntax of a programming language is not as important as the semantics, but good understanding of the syntax often helps in understanding the language. With some practice one can often guess the semantics from the syntax, since the syntax of a well-designed programming language is the frame that suppor...
algorithms and data structures.pdf
such as syntax diagrams. EBNF and syntax diagrams are syntactic notations that describe exactly the context-free grammars of formal language theory. Recursion is a central theme of all these notations: the syntactic correctness and structure of a large program text are reduced to the syntactic correctness and st...
algorithms and data structures.pdf
by writing it in an oval: Nonterminal symbols represent syntactic entities: statements, declarations, or expressions. Each nonterminal symbol is given a name consisting of a sequence of letters and digits, where the first character must be a letter. In syntax diagrams a nonterminal symbol is represented by writing ...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License For each nonterminal symbol there must be at least one production that describes how this syntactic entity is formed from other terminal or nonterminal symbols using the composition constructs above: The following examples show productions and the...
algorithms and data structures.pdf
nts Nonterminal symbol that denotes a syntactic entity. It consists of a sequence of letters and digits where the first character must be a letter. ts Terminal symbol that belongs to the defined language's vocabulary. Since the vocabulary depends on the language to be defined there is no production for ts. EBNF is no...
algorithms and data structures.pdf
6. Syntax stmt = nts '=' expr '.' . expr = term { '|' term } . term = factor { factor } . factor = nts | ts | '(' expr ')' | '[' expr ']' | '{' expr '}' . nts= letter { letter | digit } . Example: syntax of simple expressions The following productions for the three nonterminals E(xpression), T(erm), and F(actor) can be...
algorithms and data structures.pdf
E = T { ( '+' | '–' ) T } . T = F { ( '·' | '/' ) F } . F = '#' | '(' E ')' . Exhibit 6.1: Syntax diagrams for simple arithmetic expressions. From the nonterminal E we can derive different expressions. In the opposite direction we start with a sequence of terminal symbols and check by syntactic analysis, or parsing, ...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 6.2: Parse tree for the expression # · ( # ) + # / # . Exercise: syntax diagrams for palindromes A palindrome is a string that reads the same when read forward or backward. Examples: 0110 and 01010. 01 is not a palindrome, as it differs f...
algorithms and data structures.pdf
binary operators (e.g. +, –, · and /) is either a primitive operand, abbreviated as #, or of the form 'E op E'. Consider a "simpler" grammar for simple, parenthesis-free expressions (Exhibit 6.4): E = '#' | E ( '+' | '–' | '·' | '/' ) E . Algorithms and Data Structures 57 A Global Text
algorithms and data structures.pdf
6. Syntax Exhibit 6.4: A syntax that generates parse trees of ambiguous structure Now the expression # · # + # can be derived from E in two different ways ( Exhibit 6.5). Such an ambiguous grammar is useless since we want to derive the semantic interpretation from the syntactic structure, and the tree at the left c...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License In doing so we change the language. The more complex grammar with three nonterminals E(xpression, T(erm), and F(actor) lets us write expressions that are only partially parenthesized and assigns to them a unique structure compatible with our prior...
algorithms and data structures.pdf
statements: if E then S and if E then S else S 1. Draw one syntax diagram that expresses both of these syntactic possibilities. 2. Show all the possible syntactic structures of the statement if E1 then if E2 then S1 else S2 3. Propose a small modification to the Pascal language that avoids the syntactic ambiguity of t...
algorithms and data structures.pdf
interpretative evaluation, and code generation all become more complicated. Parenthesis-free or Polish notation (named for the Polish logician Jan Lukasiewicz) is a simpler notation for arithmetic expressions. All operators are systematically written either before ( prefix notation) or after ( postfix or suffix nota...
algorithms and data structures.pdf
Postfix ab+ abc·+ ab+c· Postfix notation mirrors the sequence of operations performed during the evaluation of an expression. 'ab+' is interpreted as: load a (find first operand); load b (find the second operand); add both. The syntax of arithmetic expressions in postfix notation is determined by the following gram...
algorithms and data structures.pdf
6. Syntax Exhibit 6.7: Suffix expressions have a unique structure even without the use of parentheses. Exercises 1. Consider the following syntax, given in EBNF: S = A. A = B | 'IF' A 'THEN' A 'ELSE' A. B = C | B 'OR' C. C = D | C 'AND' D. D = 'x' | '(' A ')' | 'NOT' D. (a) Determine the sets of terminal and nontermin...
algorithms and data structures.pdf
(a) The unary minus is denoted by a different character than the binary minus, say ¬. (b) The character – is 'overloaded' (i.e. it is used to denote both unary and binary minus). For any specific occurrence of –, only the context determines which operator it designates. 3. Extended Backus-Naur form and syntax diagram...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License L ::= a | b | … | z Letter D ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 Digit S ::= D { D } Sequence of digits I ::= L { L | D } Identifier (a) Real numbers (constants) in Pascal Examples: –3 + 3.14 10e–06 –10.0e6 but not 10e6 (b) Nonnested l...
algorithms and data structures.pdf
Examples: "" () ()() ()(()) ()(()())()() 4. Use both syntax diagrams and EBNF to define the repeated if-then-else statement: if B1 then S1 elsif B2 then S2 elsif … else S Algorithms and Data Structures 61 A Global Text
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 7. Syntax analysis Learning objectives: • syntax is the frame that carries the semantics of a language • syntax analysis • syntax tree • top-down parser • syntax analysis of parenthesis-free expressions by counting • syntax analysis by recursive des...
algorithms and data structures.pdf
science are syntax-driven in this sense. Hence syntax analysis is important. In this section we derive algorithms for syntax analysis directly from syntax diagrams. These algorithms reflect the recursive nature of the underlying grammars. A program for syntax analysis is called a parser. The composition of a sente...
algorithms and data structures.pdf
production for E tells us that we obtain an E if we find a sequence of T's separated by + or –. Hence we look for T's. The structure tree of an expression grows in this way as a sequence of goals from top (the root) to bottom (the leaves). While satisfying the goals (nonterminal symbols) the parser reads suitable s...
algorithms and data structures.pdf
7. Syntax analysis input symbol and the nonterminal to be expanded determine uniquely the production to be applied. A recursive- descent parser uses a set of recursive procedures to recognize its input with no backtracking. Bottom-up methods build the structure tree from the leaves to the root. The text is reduced unt...
algorithms and data structures.pdf
ti+1 = ti – 1, if i > 0 and ci+1 is an operator. Example of a correct expression: # # # # – – + # · c1 c2 c3c4c5c6c7c8c9 t0 t1 t2t3t4t5t6t7t8t9 0 1 2 3 4 3 2 1 2 1 Example of an incorrect expression (one operator is missing): # # # + · # # / c1 c2 c3 c4 c5 c6 c7 c8 t0 t1 t2 t3 t4 t5 t6 t7 t8...
algorithms and data structures.pdf
Base of induction: For n = 1 the only correct postfix expression is c 1 = #, and the sequence t 0 = 0, t 1 = 1 has the desired properties. Induction hypothesis: The theorem is correct for all expressions of length ≤ m. Induction step: Consider a correct postfix expression S of length m + 1 > 1 over the given alphabe...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License s = s0 , s1 , s2 , … , sj , sj + 1 , sj + 2 , … , sm , sm+1 t0 , t1 , t2 , … , tj , u1 + 1 , u2 + 1 , … , uk + 1 , 1 0, … ,1,… ,2,1 Since t ends with 1, we add 1 to each element in u, and the subsequence therefore ends with u k + 1 = 2. Finally...
algorithms and data structures.pdf
c1 = #, which is a correct arithmetic expression in postfix notation. Induction hypothesis: The theorem is correct for all expressions of length ≤ m. Induction step: Let s = (si) 0 ≤ i ≤ m+1 be the integer sequence associated with a string S = c 1 c2 … cm+1 of length m + 1 > 1 over the given alphabet A which satisfies...
algorithms and data structures.pdf
expressions, S = T U Op is also a correct postfix expression, and the theorem is proved. A similar proof shows that the syntactic structure of a postfix expression is unique. The integer sequence associated with a postfix expression is of practical importance: The sequence describes the depth of the stack duri...
algorithms and data structures.pdf
progress of the analysis depends on the current state and the next symbol to be read: a lookahead of exactly one symbol suffices to avoid backtracking. In Exhibit 7.3 we move one step to the right after each symbol has been recognized, and we move vertically to step up or down in the recursion. Algorithms and Dat...
algorithms and data structures.pdf
7. Syntax analysis Exhibit 7.2: Standard syntax for simple arithmetic expressions (graphic does not match) Exhibit 7.3: Trace of syntax analysis algorithm parsing the expression # · ( # – # ). Turning syntax diagrams into a parser In a programming language that allows recursion the three syntax diagrams for simple ar...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License The procedures that follow must be embedded into a program that provides the variable 'ch' and the procedures 'read' and 'error'. We assume that the procedure 'error' prints an error message and terminates the program. In a more sophisticated im...
algorithms and data structures.pdf
“Example: syntax of a simple expressions” into corresponding prefix and postfix expressions as defined in chapter 6 in the section “Parenthesis-free notation for arithmetic expressions”. Same for the inverse translations. 2. Using syntax diagrams and EBNF define a language of 'correctly nested parenthes...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Part III: Objects, algorithms, programs Computing with numbers and other objects Since the introduction of computers four or five decades ago the meaning of the word computation has kept expanding. Whereas "computation" traditionally implied "nu...
algorithms and data structures.pdf
and matrices. Programs were characterized by long execution times but small sets of input and output data. Algorithms were more important than data structures, and many new numerical algorithms were invented. Lasting achievements of this first phase of computer applications include systematic study of numer...
algorithms and data structures.pdf
moving, and printing of data. In other words, these applications are data intensive rather than computation intensive. By focusing attention on the problem of efficient management of large, dynamically varying data collections, this phase created one of the core disciplines of computer sc...
algorithms and data structures.pdf
applications such as computer-aided design (CAD) and image processing and pattern recognition (in medicine, cartography, robot control). The young discipline of computational geometry has emerged in response to the growing importance of processing geometric and pictorial objects. It has created n...
algorithms and data structures.pdf
and the best way to gain such knowledge is to study the main ideas that make standard programs work. Algorithms and Data Structures 67 A Global Text
algorithms and data structures.pdf
7. Syntax analysis Algorithms and programs Theoretical computer science treats algorithm as a formal concept, rigorously defined in a number of ways, such as Turing machines or lambda calculus. But in the context of programming, algorithm is typically used as an intuitive concept designed to help people expr...
algorithms and data structures.pdf
We present algorithms in whatever notation appears to convey the key ideas most clearly, and we have a clear preference for pictures. We present programs in an extended version of Pascal; readers should have little difficulty translating this into any programming language of their choice. Mastery of interesting sma...
algorithms and data structures.pdf
unabated, particularly in the increasingly important field of parallel algorithms. The cutting edge of algorithm research is published in several journals that specialize in this research topic, including the Journal of Algorithms and Algorithmica. This literature is generally accessible only after a stude...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 8. Truth values, the data type 'set', and bit acrobatics Learning objectives: • truth values, bits • boolean variables and functions • bit sum: four clever algorithms compared • trade-off between time and space Bits and boolean functions The Englis...
algorithms and data structures.pdf
domain, represented by yes/no, 1/0, true/false, T/F. In the late 1940s, as the use of binary arithmetic became standard and as information theory came to regard a two-valued quantity as the natural unit of information, the concise term bit was coined as an abbreviation of "binary digit". A bit, by any other name, i...
algorithms and data structures.pdf
boolean results. There are only four distinct boolean functions of a single boolean variable, among which 'not' is the most useful: It yields the complement of its argument (i.e. turns 0 into 1, and vice versa). The other three are the identity and the functions that yield the constants 0 and 1. There are 16 distin...
algorithms and data structures.pdf
8. Truth values, the data type 'set', and bit acrobatics parenthesized, precedence relations are defined on these operators: 'not' takes precedence over 'and', which takes precedence over 'or'. Thus x and not y or not x and y ⇔ ((x and (not y)) or ((not x) and y)). What can you compute with boolean variables? Theo...
algorithms and data structures.pdf
efficiently without the use of a temporary variable. The operator exclusive-or, often abbreviated as 'xor', is defined as x xor y = x and not y or not x and y. It yields true iff exactly one of its two arguments is true. The bitwise boolean operation z:= x op y on n-bit registers: x[1 .. n], y[1 .. n], z[1 .. n], is ...
algorithms and data structures.pdf
correctly for all possible values of x and y. Exhibit 8.1: Trace of registers x and y under repeated exclusive-or operations. Exercise: planar circuits without crossover of wires The code above has yet another interpretation: How should we design a logical circuit that effects a logical crossover of two wires x and y...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License The bit sum or "population count" A computer word is a fixed-length sequence of bits, call it a bit vector. Typical word lengths are 16, 32, or 64, and most instructions in most computers operate on all the bits in a word at the same time, in paral...
algorithms and data structures.pdf
moment: a bit string, an integer, or a set. We are well aware of the dangers of such ambiguous interpretations: Programs become system and compiler dependent, and thus lose portability. If such ambiguity is localized in a single, small procedure, the danger may be kept under control, and the gain in efficiency may ...
algorithms and data structures.pdf
on single bits using the boolean operators. The union of two sets of type S is obtained by applying bitwise 'or', the intersection by applying bitwise 'and'. The complement of a set is obtained by applying bitwise 'not'. Example M = {0, 1, … , 7} Set Bit vector 7 6 5 ...
algorithms and data structures.pdf
Asking for the number of elements in a set s is therefore the same as asking for the number of 1's in the bit pattern that represents s. The operation that counts the number of elements in a set, or the number of 1's in a word, is called the population count or bit sum. The bit sum is frequently used in...
algorithms and data structures.pdf
8. Truth values, the data type 'set', and bit acrobatics Inspect every bit function bitsum0(w: w16): integer; var i, c: integer; begin c := 0; for i := 0 to 15 do { inspect every bit } if i ∈ w {w[i] = 1} then c := c + 1; { count the ones} return(c) end; Skip the zeros Is there a faster way? The following al...
algorithms and data structures.pdf
executed once, the rightmost 1 of w is replaced by 0: w 1000100011001000 w – 1 1000100011000111 w ∩ (w – 1) 1000100011000000 This clever code seems to look at the 1's only and skip over all the 0's: Its loop is executed only as many times as there are 1's in the word. This savings is worthwhile for long, sparsel...
algorithms and data structures.pdf
knows how sets and integers are represented internally). function bitsum1(w: w16): integer; var c, i: integer; w0, w1: w16; begin w0 := w; c := 0; while w0 ≠ Ø { empty set } do begin i := w16toi(w0); { w16toi converts type w16 to integer } i := i – 1; w1 := itow16(i); { itow16 converts type integer to w16 } w0...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Most languages provide some facility for permitting purely formal type conversions that result in no work: 'EQUIVALENCE' statements in Fortran, 'UNSPEC' in PL/1, variant records in Pascal. Such "conversions" are done merely by interpreting the c...
algorithms and data structures.pdf
of n = 2h bits, and let S(w) be the bit sum of the bit string w. Split w into two halves and denote its left part by wL and its right part by wR. The bit sum obviously satisfies the recursive equation S(w) = S(wL) + S(wR). Repeating the same argument on the substrings wL and wR, and, in turn, on the substrings they...
algorithms and data structures.pdf
= ⎡log2 n⎤ . To obtain a logarithmic bit sum, we apply the additional trick of performing many additions in parallel. Notice that the total length of all operands on the same level is always n. Thus we can pack them into a single word and, if we arrange things cleverly, perform all the additions at the same level i...
algorithms and data structures.pdf
corresponding parts. Thus if the operations of addition and shifting operate on words of length n, a single one of these operations can be interpreted as performing many of the same operations on the shorter parts into which w has been split. This logarithmic speedup works up to the word length of the computer. For...
algorithms and data structures.pdf
8. Truth values, the data type 'set', and bit acrobatics Exhibit 8.4: All processes generated by divide-and-conquer are performed in parallel on shared data registers. The algorithm is best explained with an example; we use n = 8. w7 w6 w5 w4 w3 w2 w1 w0 w 1 1 0 1 0 0 0 1 First, extract the even-indexed bits w 6 w4 w...
algorithms and data structures.pdf
w' 1 0 0 1 0 0 0 1 Next, we index not bits, but pairs of bits, from right to left: (w' 1 w'0) is the zeroth pair, (w'5 w'4) is the second pair. Extract the even-indexed pairs w'5 w'4 and w'1 w'0, and place a pair of zeros to the left of each pair to obtain w'even. 74
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License w'5 w'4 w'1 w'0 w'even 0 0 0 1 0 0 0 1 Next, extract the odd-indexed pairs w' 7 w'6 and w'3 w'2 , shift them right by two places into bit positions w' 5 w'4 and w'1 w'0 , respectively, and insert a pair of zeros to the left of each pair to obtain...
algorithms and data structures.pdf
w"odd 0 0 0 0 0 0 1 1 Finally, numerically add w"even and w"odd to obtain w''' = (00000100), which is the representation in base 2 of the bit sum of w (4 in this example). The following function implements this algorithm. Logarithmic bit sum implemented for a 16-bit computer: In 'bitsum2' we apply addition and divisi...
algorithms and data structures.pdf
8. Truth values, the data type 'set', and bit acrobatics Trade-off between time and space: the fastest algorithm Are th ere still faster algorithms for computing the bit sum of a word? Is there an optimal algorithm? The question of optimality of algorithms is important, but it can be answered only in special cases. ...
algorithms and data structures.pdf
of memory space (2 n locations), thereby making the algorithm impractical except for small values of n. The choice of an algorithm almost always involves trade-offs among various desirable properties, and the better an algorithm is from one aspect, the worse it may be from another. The algorithm is based on the idea...
algorithms and data structures.pdf
us an algorithm that requires only one memory reference. Table lookup implemented for a 16-bit computer: function bitsum3(w: w16): integer; const c: array[0 .. 65535] of integer = [0, 1, 1, 2, 1, 2, 2, 3, … , 15, 16]; begin return(c[w]) end; In concluding this exa mple, we notice the variety of algorithms that exis...
algorithms and data structures.pdf
programmer's wits. Exercises 1. Show that there are exactly 16 distinct boolean functions of two variables. 2. Show that each of the boolean functions 'nand' and 'nor' is universal in the following sense: Any boolean function f(x, y) can be written as a nested expression involving only 'nands', and it can also be wri...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 3. Consider the logarithmic bit sum algorithm, and show that any strategy for splitting w (not just the halving split) requires n – 1 additions. Algorithms and Data Structures 77 A Global Text
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License 9. Ordered sets Learning objectives: • searching in ordered sets • sequential search. proof of program correctness • binary search • in-place permutation • nondeterministic algorithms • cycle rotation • cycle clipping Sets of elements processed on...
algorithms and data structures.pdf
programmer explicitly deals with issues of how to order a set and how to use any existing order to advantage. Searching in ordered sets is one of the most frequent tasks performed by computers: whenever we operate on a data item, that item must be selected from a set of items. Searching is also an ideal ground for il...
algorithms and data structures.pdf
const n = … ; { n > 0 } type index = 0 .. n; elt = … ; var A: array[1 .. n] of elt; or var A: array[0 .. n] of elt; Sequential or linear search is the simplest technique for determining whether A contains a given element x. It is a trivial example of an incremental algorithm, which processes a set of data ...
algorithms and data structures.pdf
9. Ordered sets (2) { (∀ k, i < k: A[k] ≠ x) ∧ ((i= 0) ∧ ((1 ≤ i ≤ n) ∧ (A[i] = x))) } return(i) end; The 'cand' operator used in the termination condition is the conditional 'and'. Evaluation proceeds from left to right and stops as soon as the value of the boolean expression is determined: If i > 0 yields 'false'...
algorithms and data structures.pdf
• i = 0 signals that the entire array has been scanned unsuccessfully. • x has been found at index i. A formal correctness proof would have to include an argument that the loop does indeed terminate—a simple argument here, since i is initialized to n, decreases by 1 in each iteration, and thus will become 0 after a f...
algorithms and data structures.pdf
convention that 0 signals an unsuccessful search: function find(x: elt): index; var i: index; begin A[0] := x; i := n; while A[i] ≠ x do i := i – 1; return(i) end; How efficient is sequential search? An unsuccessful search always scans the entire array. If all n array elements have equal probability of being se...
algorithms and data structures.pdf
provides more information than it does in the unordered case. The result x ≠ A[m] excludes not only A[m], but also all elements on one or the other side of A[m], depending on whether x is greater or smaller than A[m] (Exhibit 9.1). 79
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 9.1: Binary search identifies regions where the search argument is guaranteed to be absent. The following function exploits this additional information: const n = … ; { n > 0 } type index = 1 .. n; elt = … ; var A: array[1 .. n] of elt;...
algorithms and data structures.pdf
to be smaller than x; A[v + 1], … , A[n] are known to be greater than x. Assertion (2), before exit from the function, states that x has been found at index m. In assertion (3), u = v + 1 signals that the interval of uncertainty has shrunk to become empty. If there exists more than one match, this algorithm will fi...
algorithms and data structures.pdf
function rbs (x, u, v: integer): integer; that returns 0 if x is not in A, and an index i such that A[i] = x if x is in A. (b) What is the maximal depth of recursive calls of 'rbs' in terms of n? Algorithms and Data Structures 80 A Global Text A[m] < x m x < A[m] m If x cannot lie in
algorithms and data structures.pdf
9. Ordered sets (c) Describe the advantages and disadvantages of this recursive binary search as compared to the iterative binary search. Exercise: searching in a partially ordered two-dimensional array Consider the n by m array: var A: array[1 .. n, 1 .. m] of integer; and assume that the integers in each row and in...
algorithms and data structures.pdf
(c) Show that your algorithm is correct and terminates, and determine its worst case time complexity. Solution (a) The algorithm compares x first with A[1, m]. If x is smaller than A[1, m], then x cannot be contained in the last column, and the search process is continued by comparing x with A[1, m – 1]. If x is grea...
algorithms and data structures.pdf
This book is licensed under a Creative Commons Attribution 3.0 License else { x = A[r, c] } {2} return(true); {3} return(false) end; (c) At positions {1}, {2}, and {3}, the invariant ∀ i, 1 ≤ i ≤ n,∀ j, 1 ≤ j ≤ m: (j > c ⇒ x ≠ A[i, j]) ∧ (i < r ⇒ x ≠ A[i, j] (∗) states that the hatched rows and columns of A do not ...
algorithms and data structures.pdf
either c becomes zero or r becomes greater than n after a finite number of steps, and the algorithm terminates. In each step, the algorithm eliminates either a row from the top or a column from the right. In the worst case it works its way from the upper right corner to the lower left corner in n + m – 1 steps, lea...
algorithms and data structures.pdf
arrays t (to) or f (from) declared as var t, f: array[1 .. n] of 1 .. n; The exhibit also shows a third representation of the same permutation: the decomposition of this permutation into cycles. The element in D[1] moves into D[4], the one in D[4] into D[3], the one in D[3] into D[1], closing a cycle that we abbre...
algorithms and data structures.pdf
9. Ordered sets Consider the problem of executing this permutation in place: Both the given data and the result are stored in the same array D, and only a (small) constant amount of auxiliary storage may be used, independently of n. Let us use the example of in-place permutation to introduce a notation that is frequ...
algorithms and data structures.pdf
sequences are matched according to length and type. The value of the i-th expression on the right is assigned to the i-th variable on the left. • All the expressions on the right-hand side are evaluated using the original values of all variables that occur in them, and the resulting values are assigned "simultaneousl...
algorithms and data structures.pdf