text stringlengths 1 7.76k | source stringlengths 17 81 |
|---|---|
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 lists of identifiers (including the empty list) Examples: () (a) (year, month, day) but not (a,(b)) and not "" (c) Nested lists of identifiers (including empty lists) Examples: in addition to the examples in part (b), we have lists such as ((),()) (a, ()) (name, (first, middle, last)) but not (a)(b) and not "" (d) Parentheses expressions Almost the same problem as part (c), except that we allow the null string, we omit identifiers and commas, and we allow multiple outermost pairs of parentheses. 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_Page_61_Chunk4601 |
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 descent • recursive coroutines The role of syntax analysis The syntax of a language is the skeleton that carries the semantics. Therefore, we will try to get as much work as possible done as a side effect of syntax analysis; for example, compiling a program (i.e. translating it from one language into another) is a mainly semantic task. However, a good language and compiler are designed in such a way that syntax analysis determines where to start with the translation process. Many processes in computer 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 sentence can be represented by a syntax tree or parse tree. The root of the tree is the start symbol; the leaves represent the sentence to be recognized. The tree describes how a syntactically correct sentence can be derived from the start symbol by applying the productions of the underlying grammar (Exhibit 7.1). Exhibit 7.1: The unique parse tree for # · # + # Top-down parsers begin with the start symbol as the goal of the analysis. In our example, "search for an E". The 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 symbols (terminal symbols) from left to right. In many practical cases a parser needs no backtrack. No backtracking is required if the current Algorithms and Data Structures 62 A Global Text # á # + # F F F T T E | algorithms and data structures_Page_62_Chunk4602 |
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 until the start symbol is obtained. Syntax analysis of parenthesis-free expressions by counting Syntax analysis can be very simple. Arithmetic expressions in Polish notation are analyzed by counting. For sake of simplicity we assume that each operand in an arithmetic expression is denoted by the single character #. In order to decide whether a given string c1 c2 … cn is a correct expression in postfix notation, we form an integer sequence t 0, t1, … , tn according to the following rule: t0 = 0. ti+1 = ti + 1, if i > 0 and ci+1 is an operand. ti+1 = ti – 1, if i > 0 and ci+1 is an operator. Example of a correct expression: # # # # – – + # · c1 c2 c3 c4 c5 c6 c7 c8 c9 t0 t1 t2 t3 t4 t5 t6 t7 t8 t9 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 0 1 2 3 2 1 2 3 2 Theorem: The string c1 c2 … cn over the alphabet A = { # , + , – , · , / } is a syntactically correct expression in postfix notation if and only if the associated integer sequence t0, t1, … , tn satisfies the following conditions: ti > 0 for 1 ≤ i < n, tn = 1. Proof ⇒: Let c1 c2 … cn be a correct arithmetic expression in postfix notation. We prove by induction on the length n of the string that the corresponding integer sequence satisfies the conditions. Base of induction: For n = 1 the only correct postfix expression is c1 = #, and the sequence t0 = 0, t1 = 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 alphabet A. Let s = (si) 0 ≤ i ≤ m+1 be the integer sequence associated with S. Then S is of the form S = T U Op, where 'Op' is an operator and T and U are correct postfix expressions of length j ≤ m and length k ≤ m, j + k = m. Let t = (t i) 0 ≤ I ≤ j and u = (ui) 0 ≤ i ≤ k be the integer sequences associated with T and U. We apply the induction hypothesis to T and U. The sequence s is composed from t and u as follows: 63 | algorithms and data structures_Page_63_Chunk4603 |
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, the operator 'Op' decreases this element by 1, and s therefore ends with sm+1 = 1. Since ti > 0 for 1 ≤ i < j and ui > 0 for 1 ≤i < k, we obtain that si > 0 for 1 ≤ i < k + 1. Hence s has the desired properties, and we have proved one direction of the theorem. Proof ⇐: We prove by induction on the length n that a string c1 c2 … cn over A is a correct arithmetic expression in postfix notation if the associated integer sequence satisfies the conditions stated in the theorem. Base of induction: For n = 1 the only sequence is t0 = 0, t1 = 1. It follows from the definition of the sequence that 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 = c1 c2 … cm+1 of length m + 1 > 1 over the given alphabet A which satisfies the conditions stated in the theorem. Let j < m + 1 be the largest index with sj = 1. Since s1 = 1 such an index j exists. Consider the substrings T = c1 c2 … cj and U = cj cj+1 … cm. The integer sequences (si) 0 ≤ i ≤ j and (si – 1) j ≤ i ≤ m associated with T and U both satisfy the conditions stated in the theorem. Hence we can apply the induction hypothesis and obtain that both T and U are correct postfix expressions. From the definition of the integer sequence we obtain that cm+1 is an operand 'Op'. Since T and U are correct postfix 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 during evaluation of the expression, and the largest number in the sequence is therefore the maximum number of storage cells needed. Analysis by recursive descent We return to the syntax of the simple arithmetic expressions of chapter 6 in the section “Example: syntax of simple expressions” (Exhibit 7.2). Using the expression # · (# – #) as an example, we show how these syntax diagrams are used to analyze any expressions by means of a technique called recursive-descent parsing. The 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 Data Structures 64 A Global Text | algorithms and data structures_Page_64_Chunk4604 |
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 arithmetic expressions can be translated directly into procedures. A nonterminal symbol corresponds to a procedure call, a loop in the diagram generates a while loop, and a selection is translated into an if statement. When a procedure wants to delegate a goal it calls another, in cyclic order: E calls T calls F calls E, and so on. Procedures implementing such a recursive control structure are often called recursive coroutines. 65 | algorithms and data structures_Page_65_Chunk4605 |
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 implementation, 'error' would return a message to the calling procedure (e.g. 'factor'). Then this error message is returned up the ladder of all recursive procedure calls active at the moment. Before the first call of the procedure 'expression', a character has to be read into 'ch'. Furthermore, we assume that a correct expression is terminated by a period: … read(ch); expression; if ch ≠ '.' then error; … Exercises 1. Design recursive algorithms to translate the simple arithmetic expressions of chapter 6 in the section “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 parentheses expressions'. You have a bit of freedom (how much?) in defining exactly what is correctly nested and what is not, but obviously your definition must include expressions such as (), ((())), (()(())), and must exclude strings such as (, )(, ()) (). 3. Design two parsing algorithms for your class of correctly nested parentheses expressions: one that works by counting, the other through recursive descent. Algorithms and Data Structures 66 A Global Text | algorithms and data structures_Page_66_Chunk4606 |
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 "numbers", today we routinely compute pictures, texts, and many other types of objects. When classified according to the types of objects being processed, three types of computer applications stand out prominently with respect to the influence they had on the development of computer science. The first generation involved numerical computing, applied mainly to scientific and technical problems. Data to be processed consisted almost exclusively of numbers, or sets of numbers with a simple structure, such as vectors 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 numerical algorithms, error analysis, the concept of program libraries, and the first high-level programming languages, Fortran and Algol. The second generation, hatched by the needs of commercial data processing, leads to the development of many new data structures. Business applications thrive on record keeping and updating, text and form processing, and report generation: there is not much computation in the numeric sense of the word, but a lot of reading, storing, 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 science: data structures, and corresponding algorithms for managing data, such as searching and sorting. We are now in a third generation of computer applications, dominated by computing with geometric and pictorial objects. This change of emphasis was triggered by the advent of computers with bitmap graphics. In turn, this leads to the widespread use of sophisticated user interfaces that depend on graphics, and to a rapid increase in 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 novel data structures and algorithms, some of which are presented in Parts V and VI. Our selection of algorithms in Part III reflects the breadth of applications whose history we have just sketched. We choose the simplest types of objects from each of these different domains of computation and some of the most concise and elegant algorithms designed to process them. The study of typical small programs is an essential part of programming. A large part of computer science consists of the knowledge of how typical problems can be solved; 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_Page_67_Chunk4607 |
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 express solutions to their problems. The formal counterpart of an algorithm is a procedure or program (fragment) that expresses the algorithm in a formally defined programming language. The process of formalizing an algorithm as a program typically requires many decisions: some superficial (e.g. what type of statement is chosen to set up a loop), some of great practical consequence (e.g. for a given range of values of n, is the algorithm's asymptotic complexity analysis relevant or misleading?). 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 small programs is the best way to get started in computer science. We encourage the reader to work the examples in detail. The literature on algorithms. The development of new algorithms has been proceeding at a very rapid pace for several decades, and even a specialist can only stay abreast with the state of the art in some subfield, such as graph algorithms, numerical algorithms, or geometric algorithms. This rapid development is sure to continue 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 student has studied a few textbooks on algorithms, such as [AHU 75], [Baa 88], [BB 88], [CLR 90], [GB 91], [HS 78], [Knu 73a], [Knu 81], [Knu 73b], [Man 89], [Meh 84a], [Meh 84b], [Meh 84c], [RND 77], [Sed 88], [Wil 86], and [Wir 86]. 68 | algorithms and data structures_Page_68_Chunk4608 |
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 English mathematician George Boole (1815–1864) became one of the founders of symbolic logic when he endeavored to express logical arguments in mathematical form. The goal of his 1854 book The Laws Of Thought was "to investigate the laws of those operations of the mind by which reasoning is performed; to give expression to them in the symbolic language of calculus. …" Truth values or boolean values, named in Boole's honor, possess the smallest possible useful domain: the binary 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, is truly a primitive data element—at a sufficient level of detail, (almost) everything that happens in today's computers is bit manipulation. Just because bits are simple data quantities does not mean that processing them is necessarily simple, as we illustrate in this section by presenting some clever and efficient bit manipulation algorithms. Boolean variables range over boolean values, and boolean functions take boolean arguments and produce 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 distinct boolean functions of two boolean variables, of which several are frequently used, in particular: 'and', 'or'; their negations 'nand', 'nor'; the exclusive-or 'xor'; and the implication '⊃'. These functions are defined as follows: a b a and b a or b a nand b a nor b a xor b a ⊃ b 0 0 0 0 1 1 0 1 0 1 0 1 1 0 1 1 1 0 0 1 1 0 1 0 1 1 1 1 0 0 0 1 Bits are the atomic data elements of today's computers, and most programming languages provide a data type 'boolean' and built-in operators for 'and', 'or', 'not'. To avoid the necessity for boolean expressions to be fully Algorithms and Data Structures 69 A Global Text | algorithms and data structures_Page_69_Chunk4609 |
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? Theoretically everything, since large finite domains can always be represented by a sufficient number of boolean variables: 16-bit integers, for example, use 16 boolean variables to represent the integer domain –215 .. 215–1. Boolean variables are often used for program optimization in practical problems where efficiency is important. Swapping and crossovers: the versatile exclusive-or Consider the swap statement x :=: y, which we use to abbreviate the cumbersome triple: t := x; x := y; y := t. On computers that provide bitwise boolean operations on registers, the swap operator :=: can be implemented 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 defined as for i := 1 to n do z[i] := x[i] op y[i] With a bitwise exclusive-or, the swap x :=: y can be programmed as x := x xor y; y := x xor y; x := x xor y; It still takes three statements, but no temporary variable. Given that registers are usually in short supply, and that a logical operation on registers is typically just as fast as an assignment, the latter code is preferable. Exhibit 8.1 traces the execution of this code on two 4-bit registers and shows exhaustively that the swap is performed 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 while avoiding any physical crossover? If we had an 'xor' gate, the circuit diagram shown in Exhibit 8.2 would solve the problem. 'xor' gates must typically be realized as circuits built from simpler primitives, such as 'and', 'or', 'not'. Design a circuit consisting of 'and', 'or', 'not' gates only, which has the effect of crossing wires x and y while avoiding physical crossover. Exhibit 8.2: Three exclusive-or gates in series interchange values on two wires. 70 | algorithms and data structures_Page_70_Chunk4610 |
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 parallel. When efficiency is of great importance, it is worth exploiting to the utmost the bit parallelism built into the hardware of most computers. Today's programming languages often fail to refer explicitly to hardware features such as registers or words in memory, but it is usually possible to access individual bits if one knows the representation of integers or other data types. In this section we take the freedom to drop the constraint of strong typing built into Pascal and other modern languages. We interpret the content of a register or a word in memory as it suits the need of the 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 outweigh these drawbacks. In Pascal, for example, the type 'set' is especially well suited to operate at the bit level. 'type s = set of (a, b, c)' consists of the 2 3 sets that can be formed from the three elements a, b, c. If the basic set M underlying the declaration of type S = set of M consists of n elements, then S has 2n elements. Usually, a value of type S is internally represented by a vector of n contiguously allocated bits, one bit for each element of the set M. When computing with values of type S we operate 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 4 3 2 1 0 Elements s1 {0, 3, 4, 6} 0 1 0 1 1 0 0 1 s2 {0, 1, 4, 5} 0 0 1 1 0 0 1 1 s1 ∪ s2 {0, 1, 3, 4, 5, 6} 0 1 1 1 1 0 1 1 s1 ∩ s2 {0, 4} 0 0 0 1 0 0 0 1 ¬ s1 {1, 2, 5, 7} 1 0 1 0 0 1 1 0 Integers are represented on many small computers by 16 bits. We assume that a type 'w16', for "word of length 16", can be defined. In Pascal, this might be type w16 = set of 0 .. 15; A variable of type 'w16' is a set of at most 16 elements represented as a vector of 16 bits. 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 inner loops of combinatorial calculations, and many a programmer has tried to make it as fast as possible. Let us look at four of these tries, beginning with the obvious. Algorithms and Data Structures 71 A Global Text | algorithms and data structures_Page_71_Chunk4611 |
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 algorithm looks mysterious and tricky. The expression w ∩ (w – 1) contains both an intersection operation '∩', which assumes that its operands are sets, and a subtraction, which assumes that w is an integer: c := 0; while w ≠ 0 do { c := c + 1; w := w ∩ (w – 1) } ; Such mixing makes sense only if we can rely on an implicit assumption on how sets and integers are represented as bit vectors. With the usual binary number representation, an example shows that when the body of the loop is 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, sparsely populated words (few 1's and many 0's). In the statement w := w ∩ (w – 1), w is used both as an integer (in w – 1) and as a set (as an operand in the intersection operation '∩'). Strongly typed languages, such as Pascal, do not allow such mixing of types. In the following function 'bitsum1', the conversion routines 'w16toi' and 'itow16' are introduced to avoid this double interpretation of w. However, 'bitsum1' is of interest only if such a type conversion requires no extra time (i.e. if one 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 := w0 ∩ w1; { intersection of two sets } c := c + 1 end; return(c) end; 72 | algorithms and data structures_Page_72_Chunk4612 |
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 contents of a given storage location in different ways. Logarithmic bit sum For a computer of word length n, the following algorithm computes the bit sum of a word w running through its loop only ⎡log2 n⎤ times, as opposed to n times for 'bitsum0' or up to n times for 'bitsum1'. The following description holds for arbitrary n but is understood most easily if n = 2h. The logarithmic bit sum works on the familiar principle of divide-and-conquer. Let w denote a word consisting 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 create, we arrive at a process to compute S(w). This process terminates when we hit substrings of length 1 [i.e. substrings consisting of a single bit b; in this case we have S(b) = b]. Repeated halving leads to a recursive decomposition of w, and the bit sum is computed by a tree of n – 1 additions as shown below for n = 4 (Exhibit 8.3). Exhibit 8.3: Logarithmic bit sum algorithm as a result of divide-and-conquer. This approach of treating both parts of w symmetrically and repeated halving leads to a computation of depth h = ⎡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 in one machine operation, an addition of two n-bit words. Exhibit 8.4 shows how a number of the additions on short strings are carried out by a single addition on long strings. S(w) now denotes not only the bit sum but also its binary representation, padded with zeros to the left so as to have the appropriate length. Since the same algorithm is being applied to wL and wR, and since wL and wR are of equal length, exactly the same operations are performed at each stage on wL and its parts as on wR and its 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 n = 64, for example, recursive splitting generates six levels and translates into six iterations of the loop below. Algorithms and Data Structures 73 A Global Text | algorithms and data structures_Page_73_Chunk4613 |
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 w6 w4 w2 w0 and place a zero to the left of each bit to obtain weven. The newly inserted zeros are shown in small type. w6 w4 w2 w0 weven 0 1 0 1 0 0 0 1 Next, extract the odd-indexed bits w7 w5 w3 w1, shift them right by one place into bit positions w6 w4 w2 w0, and place a zero to the left of each bit to obtain wodd. w7 w5 w3 w1 wodd 0 1 0 0 0 0 0 0 Then, numerically add weven and wodd, considered as integers written in base 2, to obtain w'. w'7 w'6 w'5 w'4 w'3 w'2 w'1 w'0 weven 0 1 0 1 0 0 0 1 wodd 0 1 0 0 0 0 0 0 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_Page_74_Chunk4614 |
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 w'odd. w'7 w'6 w'3 w'2 w'odd 0 0 1 0 0 0 0 0 Numerically, add w'even and w'odd to obtain w". w"7 w"6 w"5 w"4 w"3 w"2 w"1 w"0 w" 0 0 1 1 0 0 0 1 Next, we index quadruples of bits, extract the quadruple w"3 w"2 w"1 w"0, and place four zeros to the left to obtain w"even. w"3 w"2 w"1 w"0 w"even 0 0 0 0 0 0 0 1 Extract the quadruple w"7 w"6 w"5 w"4, shift it right four places into bit positions w"3 w"2 w"1 w"0, and place four zeros to the left to obtain w"odd. w"7 w"6 w"5 w"4 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 division operations directly to variables of type 'w16' without performing the type conversions that would be necessary in a strongly typed language such as Pascal. function bitsum2(w: w16): integer; const mask[0] = '0101010101010101'; mask[1] = '0011001100110011'; mask[2] = '0000111100001111'; mask[3] = '0000000011111111'; var i, d: integer; weven, wodd: w16; begin d := 2; for i := 0 to 3 do begin weven := w ∩ mask[i]; w := w / d; { shift w right 2i bits } d := d2; wodd := w ∩ mask[i]; w := weven + wodd end; return(w) end; Algorithms and Data Structures 75 A Global Text | algorithms and data structures_Page_75_Chunk4615 |
8. Truth values, the data type 'set', and bit acrobatics Trade-off between time and space: the fastest algorithm Are there 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. To show that an algorithm is optimal, one must specify precisely the class of algorithms allowed and the criterion of optimality. In the case of bit sum algorithms, such specifications would be complicated and largely arbitrary, involving specific details of how computers work. However, we can make a plausible argument that the following bit sum algorithm is the fastest possible, since it uses a table lookup to obtain the result in essentially one operation. The penalty for this speed is an extravagant use of memory space (2n 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 that we can precompute the solutions to all possible questions, store the results, and then simply look them up when needed. As an example, for n = 3, we would store the information Word Bit sum 0 0 0 0 0 0 1 1 0 1 0 1 0 1 1 2 1 0 0 1 1 0 1 2 1 1 0 2 1 1 1 3 What is the fastest way of looking up a word w in this table? Under assumptions similar to those used in the preceding algorithms, we can interpret w as an address of a memory cell that contains the bit sum of w, thus giving 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 example, we notice the variety of algorithms that exist for computing the bit sum, each one based on entirely different principles, giving us a different trade-off between space and time. 'bitsum0' and 'bitsum3' solve the problem by "brute force" and are simple to understand: 'bitsum0' looks at each bit and so requires much time; 'bitsum3' stores the solution for each separate case and thus requires much space. The logarithmic bit sum algorithm is an elegant compromise: efficient with respect to both space and time, it merely challenges the 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 written using only 'nors'. Show that no other boolean function of two variables is universal. 76 | algorithms and data structures_Page_76_Chunk4616 |
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_Page_77_Chunk4617 |
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 a computer are always ordered according to some criterion. In the preceding example of the "population count" operation, a set is ordered arbitrarily and implicitly simply because it is mapped onto linear storage; a programmer using that set can ignore any order imposed by the implementation and access the set through functions that hide irrelevant details. In most cases, however, the order imposed on a set is not accidental, but is prescribed by the problem to be solved and/or the algorithm to be used. In such cases the 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 illustrating basic concepts and techniques of programming. At times, ordered sets need to be rearranged (permuted). The chapter “Sorting and its complexity” is dedicated to the most frequent type of rearrangement: permuting a set of elements into ascending order. Here we discuss another type of rearrangement: reordering a set according to a given permutation. Sequential search Consider the simple case where a fixed set of n data elements is given in an array A: 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 one element at a time. If the search for x is successful, we return an index i, 1 ≤ i ≤ n, to point to x. The convention that i = 0 signals unsuccessful search is convenient and efficient, as it encodes all possible outcomes in a single parameter. function find(x: elt): index; var i: index; begin i := n; while (i > 0) { can access A } cand (A[i] ≠ x) { not yet found } do (1) { (1 ≤ i ≤ n) ∧ (∀ k, i ≤ k: A[k] ≠ x) } i := i – 1; Algorithms and Data Structures 78 A Global Text | algorithms and data structures_Page_78_Chunk4618 |
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', we immediately terminate evaluation of the boolean expression without accessing A[i], thus avoiding an out-of-bounds error. We have included two assertions, (1) and (2), that express the main points necessary for a formal proof of correctness: mainly, that each iteration of the loop extends by one element the subarray known not to contain the search argument x. Assertion (1) is trivially true after the initialization i := n, and remains true whenever the body of the while loop is about to be executed. Assertion (2) states that the loop terminates in one of two ways: • 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 finite number of steps. The loop is terminated by a Boolean expression composed of two terms: reaching the end of the array, i = 0, and testing the current array element, A[i] = x. The second term is unavoidable, but the first one can be spared by making sure that x is always found before the index i drops off the end of the array. This is achieved by extending the array by one cell A[0] and placing the search argument x in it as a sentinel. If no true element x stops the scan of the array, the sentinel will. Upon exit from the loop, the value of i reveals the outcome of the search, with the 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 searched for, the average number of iterations of the while loop in a successful search is This algorithm needs time proportional to n in the average and the worst case. Binary search If the data elements stored in the array A are ordered according to the order relation ≤ defined on their domain, that is ∀ k, 1 ≤ k < n: A[k] ≤ A[k + 1] the search for an element x can be made much faster because a comparison of x with any array element A[m] 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_Page_79_Chunk4619 |
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; function find(x: elt; var m: index): boolean; var u, v: index; begin u := 1; v := n; while u ≤ v do begin (1) { (u ≤ v) ∧ (∀ k, 1 ≤ k < u: A[k] < x) ∧(∀ k, v < k ≤ n: A[k] > x) } m := any value such that u ≤ m ≤ v ; if x < A[m] thenv := m – 1 elsif x > A[m] then u := m + 1 (2) else {x = A[m] } return(true) end; (3) { (u = v + 1) ∧(∀ k, 1 ≤ k < u: A[k]< x) ∧ (∀ k, v < k ≤ n: A[k] > x) } return(false) end; u and v bound the interval of uncertainty that might contain x. Assertion (1) states that A[1], … , A[u – 1] are known 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 find one of them. This algorithm is correct independently of the choice of m but is most efficient when m is the midpoint of the current search interval: m := (u + v) div 2; With this choice of m each comparison either finds x or eliminates half of the remaining elements. Thus at most ⎡log2 n⎤ iterations of the loop are performed in the worst case. Exercise: binary search The array var A: array [1 .. n] of integer; contains n integers in ascending order: A[1] ≤ A[2] ≤ … ≤ A[n]. (a) Write a recursive binary search 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_Page_80_Chunk4620 |
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 each column are in ascending order; that is, A[i, j] ≤ A[i, j + 1]for i = 1, … , n and j = 1, … , m – 1; A[i, j] ≤ A[i + 1, j]for i = 1, … , n – 1 and j = 1, … , m. (a) Design an algorithm that determines whether a given integer x is stored in the array A. Describe your algorithm in words and figures. Hint: Start by comparing x with A[1, m] (Exhibit 9.2). Exhibit 9.2: Another example of the idea of excluded regions. (b) Implement your algorithm by a function IsInArray (x: integer): boolean; (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 greater than A[1, m], then x cannot be contained in the first row, and the search process is continued by comparing x with A[2, m]. Exhibit 9.3 shows part of a typical search process. Exhibit 9.3: Excluded regions combine to leave only a staircase-shaped strip to examine. (b) function IsInArray(x: integer): boolean; var r, c: integer; begin r := 1; c := m; while (r ≤ n) and (c ≥ 1) do {1} if x < A[r, c] then c := c – 1 elsif x > A[r, c] then r := r + 1 81 | algorithms and data structures_Page_81_Chunk4621 |
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 contain x. At {2}, (1 ≤ r ≤ n) ∧ (1 ≤ c ≤ m) ∧ (x = A[r, c]) states that r and c are within index range and x has been found at (r, c). At {3}, (r = n + 1) ∨(c = 0) states that r or c are outside the index range. This coupled with (*) implies that x is not in A: (r = n + 1) ∨ (c = o) ⇒ ∀ i, 1 ≤ i ,≤ n, ∀ j. 1 ≤ j ≤ m: x ≠ A[i, j]. Each iteration through the loop either decreases c by one or increases r by one. If x is not contained in the array, 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, leading to a complexity of Θ(n + m). In-place permutation Representations of a permutation. Consider an array D[1 .. n] that holds n data elements of type 'elt'. These are ordered by their position in the array and must be rearranged according to a specific permutation given in another array. Exhibit 9.4 shows an example for n = 5. Assume that a, b, c, d, e, stored in this order, are to be rearranged in the order c, e, d, a, b. This permutation is represented naturally by either of the two permutation 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 abbreviate as (1 4 3), or (4 3 1), or (3 1 4). There is another cycle (2 5), and the entire permutation is represented by (1 4 3) (2 5). Exhibit 9.4: A permutation and its representations in terms of 'to', 'from', and cycles. The cycle representation is intuitively most informative, as it directly reflects the decomposition of the problem into independent subproblems, and both the 'to' and 'from' information is easily extracted from it. But 'to' and 'from' dispense with parentheses and lead to more concise programs. Algorithms and Data Structures 82 A Global Text | algorithms and data structures_Page_82_Chunk4622 |
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 frequently convenient, and to illustrate how the choice of primitive operations affects the solution. A multiple assignment statement will do the job, using either 'to' or 'from': // (1 ≤ i ≤ n) { D[t[i]] := D[i] } or // (1 ≤ i ≤ n) { D[i]} := D[f[i]] } The characteristic properties of a multiple assignment statement are: • The left-hand side is a sequence of variables, the right-hand side is a sequence of expressions, and the two 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 "simultaneously" to the variables on the left-hand side. We use the sign // to designate concurrent or parallel execution. Few of today's programming languages offer multiple assignments, in particular those of variable length used above. Breaking a multiple assignment into single assignments usually forces the programmer to introduce temporary variables. As an example, notice that the direct sequentialization: for i := 1 to n do D[t[i]] := D[i] or for i := 1 to n do D[i] := D[f[i]] is faulty, as some of the elements in D will be overwritten before they can be moved. Overwriting can be avoided at the cost of nearly doubling memory requirements by allocating an array A[1 .. n] of data elements for temporary storage: for i := 1 to n do A[t[i]] := D[i]; for i := 1 to n do D[i] := A[i]; This, however, is not an in-place computation, as the amount of auxiliary storage grows with n. It is unnecessarily inefficient: There are elegant in-place permutation algorithms based on the conventional primitive of the single assignment statement. They all assume that the permutation array may be destroyed as the permutation is being executed. If the representation of the permutation must be preserved, additional storage is required for bookkeeping, typically of a size proportional to n. Although this additional space may be as little as n bits, perhaps in order to distinguish the elements processed from those yet to be moved, such an algorithm is not technically in place. Nondeterministic algorithms. Problems of rearrangement always appear to admit many different solutions —a phenomenon that is most apparent when one considers the multitude of sorting algorithms in the literature. The reason is clear: When n elements must be moved, it may not matter much which elements are moved first and which ones later. Thus it is useful to look for nondeterministic algorithms that refrain from specifying the precise sequence of all actions taken, and instead merely iterate condition ⇒ action statements, with the meaning "wherever condition applies perform the corresponding action". These algorithms are nondeterministic because each of several distinct conditions may apply at lots of different places, and we may "fire" any action that is 83 | algorithms and data structures_Page_83_Chunk4623 |
This book is licensed under a Creative Commons Attribution 3.0 License currently enabled. Adding sequential control to a nondeterministic algorithm turns it into a deterministic algorithm. Thus a nondeterministic algorithm corresponds to a class of deterministic ones that share common invariants, but differ in the order in which steps are executed. The correctness of a nondeterministic algorithm implies the correctness of all its sequential instances. Thus it is good algorithm design practice to develop a correct nondeterministic algorithm first, then turn it into a deterministic one by ordering execution of its steps with the goal of efficiency in mind. Deterministic sequential algorithms come in a variety of forms depending on the choice of primitive (assignment or swap), data representation ('to' or 'from'), and technique. We focus on the latter and consider two techniques: cycle rotation and cycle clipping. Cycle rotation follows naturally from the idea of decomposing a permutation into cycles and processing one cycle at a time, using temporary storage for a single element. It fits the 'from' representation somewhat more efficiently than the 'to' representation, as the latter requires a swap of two elements where the former uses an assignment. Cycle clipping uses the primitive 'swap two elements' so effectively as a step toward executing a permutation that it needs no temporary storage for elements. Because no temporary storage is tied up, it is not necessary to finish processing one cycle before starting on the next one–elements can be clipped from their cycles in any order. Clipping works efficiently with either representation, but is easier to understand with 'to'. We present cycle rotation with 'from' and cycle clipping with 'to' and leave the other two algorithms as exercises. Cycle rotation A search for an in-place algorithm naturally leads to the idea of processing a permutation one cycle at a time: every element we place at its destination bumps another one, but we avoid holding an unbounded number of bumped elements in temporary storage by rotating each cycle, one element at a time. This works best using the 'from' representation. The following loop rotates the cycle that passes through an arbitrary index i: Rotate the cycle starting at index i, updating f: j := i;{ initialize a two-pronged fork to travel along the cycle } p := f[j]; { p is j's predecessor in the cycle } A := D[j]; { save a single element in an auxiliary variable A } while p ≠ i do { D[j] := D[p]; f[j] := j; j := p; p := f[j]} ; D[j] := A; { reinsert the saved element into the former cycle … } f[j] := j; { … but now it is a fixed point } This code works trivially for a cycle of length 1, where p = f[i] = i guards the body of the loop from ever being executed. The statement f[j] := j in the loop is unnecessary for rotating the cycle. Its purpose is to identify an element that has been placed at its final destination, so this code can be iterated for 1 ≤ i ≤ n to yield an in-place permutation algorithm. For the sake of efficiency we add two details: (1) We avoid unnecessary movements A := D[j]; D[j] := A of a possibly voluminous element by guarding cycles of length 1 with the test 'i ≠ f[i]', and (2) we terminate the iteration at n – 1 on the grounds that when n – 1 elements of a permutation are in their correct place, the n-th one is also. Using the code above, this leads to for i := 1 to n – 1 do if i ≠ f[i] then rotate the cycle starting at index i, updating f Exercise Implement cycle rotation using the 'to' representation. Hint: Use the swap primitive rather than element assignment. Algorithms and Data Structures 84 A Global Text | algorithms and data structures_Page_84_Chunk4624 |
9. Ordered sets Cycle clipping Cycle clipping is the key to elegant in-place permutation using the 'to' representation. At each step, we clip an arbitrary element d out of an arbitrary cycle of length > 1, thus reducing the latter's length by 1. As shown in Exhibit 9.5, we place d at its destination, where it forms a cycle of length 1 that needs no further processing. The element it displaces, c, can find a (temporary) home in the cell vacated by d. It is probably out of place there, but no more so than it was at its previous home; its time will come to be relocated to its final destination. Since we have permuted elements, we must update the permutation array to reflect accurately the permutation yet to be performed. This is a local operation in the vicinity of the two elements that were swapped, somewhat like tightening a belt by one notch —all but two of the elements in the clipped cycle remain unaffected. The Exhibit below shows an example. In order to execute the permutation (1 4 3) (2 5), we clip d from its cycle (1 4 3) by placing d at its destination D[3], thus bumping c into the vacant cell D[4]. This amounts to representing the cycle (1 4 3) as a product of two shorter cycles: the swap (3 4), which can be done right away, and the cycle (1 4) to be executed later. The cycle (2 5) remains unaffected. The ovals in Exhibit 9.5 indicate that corresponding entries of D and t are moved together. Exhibit 9.6 shows what happens to a cycle clipped by a swap // { t[i], D[i] :=: t[t[i]], D[t[i]] } Exhibit 9.5: Clipping one element out of a cycle of a permutation. Exhibit 9.6: Effect of a swap caused by the condition i ≠ t[i]. 85 | algorithms and data structures_Page_85_Chunk4625 |
This book is licensed under a Creative Commons Attribution 3.0 License Cycles of length 1 are left alone, and the absence of cycles of length > 1 signals termination. Thus the following condition ⇒ action statement, iterated as long as the condition i ≠ t[i] can be met, executes a permutation represented in the array t: ∃ i:i ≠ t[i] ⇒ // { t[i], D[i] :=: t[t[i]], D[t[i]] } We use the multiple swap operator // { :=: } with the meaning: evaluate all four expressions using the original values of all the variables involved, then perform all four assignments simultaneously. It can be implemented using six single assignments and two auxiliary variables, one of type 1 .. n, the other of type 'elt'. Each swap places (at least) one element into its final position, say j, where it is guarded from any further swaps by virtue of j = t[j]. Thus the nondeterministic algorithm above executes at most n – 1 swaps: When n – 1 elements are in final position, the n-th one is also. The conditions on i can be checked in any order, as long as they are checked exhaustively, for example: { (0) (1 ≤ j < 0) ⇒ j = t[j] } for i := 1 to n – 1 do { (1) (1 ≤ j < i) ⇒ j = t[j] } while i ≠ t[i] do // { t[i], D[i] :=: t[t[i]], D[t[i]] } { (2) (1 ≤ j ≤ i) ⇒ j = t[j] } { (3) (1 ≤ j ≤ n – 1) ⇒ j = t[j] } For each value of i, i is the leftmost position of the cycle that passes through i. As the while loop reduces this cycle to cycles of length 1, all swaps involve i and t[i] > i, as asserted by the invariant (1) (1 ≤ j < I) ⇒ j = t[j], which precedes the while loop. At completion of the while loop, the assertion is strengthened to include i, as stated in invariant (2) (1 ≤ j ≤ I) ⇒ j = t[j]. This reestablishes (1) for the next higher value of i. The vacuously true assertion (0) serves as the basis of this proof by induction. The final assertion (3) is just a restatement of assertion (2) for the last value of i. Since t[1] … t[n] is a permutation of 1 …n, (3) implies that n = t[n]. Exercise: cycle clipping using the 'from' representation The nondeterministic algorithm expressed as a multiple assignment // (1 ≤ i ≤ n) { D[i]} := D[f[i]] } is equally as valid for the 'from' representation as its analog // (1 ≤ i ≤ n) { D[t[i]] := D[i] } was for the 'to' representation. But in contrast to the latter, the former cannot be translated into a simple iteration of the condition ⇒ action statement: ∃ i: i ≠ f[i] ⇒ // { f[i], D[i] :=: f[f[i]], D[f[i]] } Why not? Can you salvage the idea of cycle clipping using the 'from' representation Exercises 1. Write two functions that implement sequential search, one with sentinel as shown in the first section, "Sequential search" the other without sentinel. Measure and compare their running time on random arrays of various sizes 2. Measure and compare the running times of sequential search and binary search on random arrays of size n, for n = 1 to n = 100. Sequential search is obviously faster for small values of n, and binary search for large n, but where is the crossover? Explain your observations. Algorithms and Data Structures 86 A Global Text | algorithms and data structures_Page_86_Chunk4626 |
This book is licensed under a Creative Commons Attribution 3.0 License 10. Strings Learning objectives: • searching for patterns in a string • finite-state machine Most programming languages support simple operations on strings (e.g. comparison, concatenation, extraction, searching). Searching for a specified pattern in a string (text) is the computational kernel of most string processing operations. Several efficient algorithms have been developed for this potentially time-consuming operation. The approach presented here is very general; it allows searching for a pattern that consists not only of a single string, but a set of strings. The cardinality of this set influences the storage space needed, but not the time. It leads us to the concept of a finite-state machine (fsm). Recognizing a pattern consisting of a single string Problem: Given a (long) string z = z1 z2 … zn of n characters and a (usually much shorter) string p = p1 p2 … pm of m characters (the pattern), find all (nonoverlapping) occurrences of p in z. By sliding a window of length m from left to right along z and examining most characters zi m times we solve the problem using m · n comparisons. By constructing a finite-state machine from the pattern p it suffices to examine each character z i exactly once, as shown in Exhibit 10.1. Each state corresponds to a prefix of the pattern, starting with the empty prefix and ending with the complete pattern. The input symbols are the input characters z1, z2, … , zn of z. In the j-th step the input character zj leads from a state corresponding to the prefix p1 p2 … pi to • the state with prefix p1 p2 … pi pi+1 if zj = pi+1 • a different state (often the empty prefix, λ) if zj ≠ pi+1 Example p = barbara (Exhibit 10.1). Exhibit 10.1: State diagram showing some of the transitions. All other state transitions lead back to the initial state. Notice that the pattern 'barbara', although it sounds repetitive, cannot overlap with any part of itself. Constructing a finite-state machine for such a pattern is straightforward. But consider a self-overlapping pattern such as 'barbar', or 'abracadabra', or 'xx', where the first k > 0 characters are identical with the last: The text 'barbarbar' contains two overlapping occurrences of the pattern 'barbar', and 'xxxx' contains three occurrences of 'xx'. A finite-state machine constructed in an analogous fashion as the one used for 'barbara' always finds the first of Algorithms and Data Structures 87 A Global Text | algorithms and data structures_Page_87_Chunk4627 |
10. Strings several overlapping occurrences but might miss some of the later ones. As an exercise, construct finite-state machines that detect all occurrences of self-overlapping patterns. Recognizing a set of strings: a finite-state-machine interpreter Finite-state machines (fsm, also called "finite automata") are typically used to recognize patterns that consist of a set of strings. An adequate treatment of this more general problem requires introducing some concepts and terminology widely used in computer science. Given a finite set A of input symbols, the alphabet, A* denotes the (infinite) set of all (finite) strings over A, including the nullstring λ. Any subset L ⊆ A*, finite or infinite, is called a set of strings, or a language, over A. Recognizing a language L refers to the ability to examine any string z ∈ A*, one symbol at a time from left to right, and deciding whether or not z ∈ L. A deterministic finite-state machine M is essentially given by a finite set S of states, a finite alphabet A of input symbols, and a transition function f: S x A → S. The state diagram depicts the states and the inputs, which lead from one state to another; thus a finite-state machine maps strings over A into sequences of states. When treating any specific problem, it is typically useful to expand this minimal definition by specifying one or more of the following additional concepts. An initial state s0 S, a subset F ⊆ S of final or accepting states, a finite alphabet B of output symbols and an output function g: S → B, which can be used to assign certain actions to the states in S. We use the concepts of initial state s0 and of accepting states F to define the notion "recognizing a set of strings": A set L ⊆ A* of strings is recognized or accepted by the finite-state machine M = (S, A, f, s0, F) iff all the strings in L, and no others, lead M from s0 to some state s ∈ F. Example Exhibit 10.3 shows the state diagram of a finite-state machine that recognizes parameter lists as defined by the syntax diagrams in Exhibit 10.2. L (letter) stands for a character a .. z, D (digit) for a digit 0 .. 9. Exhibit 10.2: Syntax diagram of simple parameter lists. 88 | algorithms and data structures_Page_88_Chunk4628 |
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 10.3: State diagram of finite-state machine to accept parameter lists. The starting state is '1', the single accepting state is '8'. A straightforward implementation of a finite-state machine interpreter uses a transition matrix T to represent the state diagram. From the current state s the input symbol c leads to the next state T[s, c]. It is convenient to introduce an error state that captures all illegal transitions. The transition matrix T corresponding to Exhibit 10.3 looks as follows: L represents a character a .. z. D represents a digit 0 .. 9. ! represents all characters that are not explicitly mentioned. ( ) : , ; L D ! 0 1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0 0 1 2 0 0 0 0 0 0 0 2 4 4 5 7 7 8 0 0 0 0 0 0 0 0 0 0 0 8 8 0 0 5 5 0 0 0 0 0 0 3 0 0 3 0 6 6 0 0 2 2 0 0 0 0 0 0 2 2 0 0 3 0 0 6 0 0 0 0 0 0 0 0 error state skip blank left parenthesis read reading variable identifier skip blank colon read reading type identifier skip blank right parenthesis read The following is a suitable environment for programming a finite-state-machine interpreter: const nstate = 8; { number of states, without error state } type state = 0 .. nstate; { 0 = error state, 1 = initial state } inchar = ' ' .. '¨'; { 64 consecutive ASCII characters } tmatrix = array[state, inchar] of state; var T: tmatrix; After initializing the transition matrix T, the procedure 'silentfsm' interprets the finite-state machine defined by T. It processes the sequence of input characters and jumps around in the state space, but it produces no output. procedure silentfsm(var T: tmatrix); var s: state; c: inchar; begin s := 1; { initial state } while s ≠ 0 do { read(c); s := T[s, c] } Algorithms and Data Structures 89 A Global Text | algorithms and data structures_Page_89_Chunk4629 |
10. Strings end; The simple structure of 'silentfsm' can be employed for a useful finite-state-machine interpreter in which initialization, error condition, input processing and transitions in the state space are handled by procedures or functions 'initfsm', 'alive', 'processinput', and 'transition' which have to be implemented according to the desired behavior. The terminating procedure 'terminate' should print a message on the screen that confirms the correct termination of the input or shows an error condition. procedure fsmsim(var T: tmatrix); var … ; begin initfsm; while alive do { processinput; transition }; terminate end; Exercise: finite-state recognizer for multiples of 3 Consider the set of strings over the alphabet {0, 1} that represent multiples of 3 when interpreted as binary numbers, such as: 0, 00, 11, 00011, 110. Design two finite-state machines for recognizing this set: • Left to right: Mlr reads the strings from most significant bit to least significant. • Right to left: Mrl reads the strings from least significant bit to most significant. Solution Left to right: Let rk be the number represented by the k leftmost bits, and let b be the (k + 1)-st bit, interpreted as an integer. Then rk+1 = 2·rk + b. The states correspond to rk mod 3 (Exhibit 10.4). Starting state and accepting state: 0'. Exhibit 10.4: Finite-state machine computes remainder modulo 3 left to right. Right to left: rk+1 = b·2k + rk. Show by induction that the powers of 2 are alternatingly congruent to 1 and 2 modulo 3 (i.e. 2k mod 3 = 1 for k even, 2k mod 3 = 2 for k odd). Thus we need a modulo 2 counter, which appears in Exhibit 10.5 as two rows of three states each. Starting state: 0. Accepting states: 0 and 0'. 90 | algorithms and data structures_Page_90_Chunk4630 |
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 10.5: Finite-state machine computes remainder modulo 3 right to left. Exercises and programming projects 1. Draw the state diagram of several finite-state machines, each of which searches a string z for all occurrences of an interesting pattern with repetitive parts, such as 'abaca' or 'Caracas'. 2. Draw the state diagram of finite-state machines that detect all occurrences of a self-overlapping pattern such as 'abracadabra', 'barbar', or 'xx'. 3. Finite-state recognizer for various days: Design a finite-state machine for automatic recognition of the set of nine words: 'monday','tuesday','wednesday','thursday', 'friday', 'saturday', 'sunday', 'day', 'daytime' in a text. The underlying alphabet consists of the lowercase letters 'a' .. 'z' and the blank. Draw the state diagram of the finite-state machine; identify the initial state and indicate accepting states by a double circle. It suffices to recognize membership in the set without recognizing each word individually. 4. Implementation of a pattern recognizer: Some useful procedures and functions require no parameters, hence most programming languages incorporate the concept of an empty parameter list. There are two reasonable syntax conventions about how to write the headers of parameterless procedures and functions: (1) procedure p; function f: T; (2) procedure p();function f(): T; Examples: Pascal uses convention (1); Modula-2 allows both (1) and (2) for procedures, but only (2) for function procedures. For each convention (1) and (2), modify the syntax diagram in Exhibit 10.2 to allow empty parameter lists, and draw the state diagrams of the corresponding finite-state machines. 5. Standard Pascal defines parameter lists by means of the syntax diagram shown in Exhibit 10.6. Algorithms and Data Structures 91 A Global Text | algorithms and data structures_Page_91_Chunk4631 |
10. Strings Exhibit 10.6: Syntax diagram for standard Pascal parameter lists. Draw a state diagram for the corresponding finite-state machine. For brevity's sake, consider the reserved words 'function', 'var' and 'procedure' to be atomic symbols rather than strings of characters. 92 | algorithms and data structures_Page_92_Chunk4632 |
This book is licensed under a Creative Commons Attribution 3.0 License 11. Matrices and graphs: transitive closure Learning objectives: • atomic versus structured objects • directed versus undirected graphs • transitive closure • adjacency and connectivity matrix • boolean matrix multiplication • efficiency of an algorithm. asymptotic notation • Warshall’s algorithm • weighted graph • minimum spanning tree In any systematic presentation of data objects, it is useful to distinguish primitive or atomic objects from composite or structured objects. In each of the preceding chapters we have seen both types: A bit, a character, or an identifier is usually considered primitive; a word of bits, a string of characters, an array of identifiers is naturally treated as composite. Before proceeding to the most common primitive objects of computation, numbers, let us discuss one of the most important types of structured objects, matrices. Even when matrices are filled with the simplest of primitive objects, bits, they generate interesting problems and useful algorithms. Paths in a graph Syntax diagrams and state diagrams are examples of a type of object that abounds in computer science: A graph consists of nodes or vertices, and of edges or arcs that connect a pair of nodes. Nodes and edges often have additional information attached to them, such as labels or numbers. If we wish to treat graphs mathematically, we need a definition of these objects. Directed graph. Let N be the set of n elements {1, 2, … , n} and E a binary relation: E N ⊆ ξ N, also denoted by an arrow, →. Consider N to be the set of nodes of a directed graph G, and E the set of arcs (directed edges). A directed graph G may be represented by its adjacency matrix A (Exhibit 11.1), an n ξ n boolean matrix whose elements A[i, j] determine the existence of an arc from i to j: A[i, j] = true iff i → j. An arc is a path of length 1. From A we can derive all paths of any length. This leads to a relation denoted by a double arrow, ⇒, called the transitive closure of E: i ⇒ j, iff there exists a path from i to j (i.e. a sequence of arcs i → i1, i1 → i2, i2 → i3, … , ik → j). We accept paths of length 0 (i.e. i ⇒ i for all i). This relation ⇒ is represented by a matrix C= A∗(Exhibit 11.1): Algorithms and Data Structures 93 A Global Text | algorithms and data structures_Page_93_Chunk4633 |
11. Matrices and graphs: transitive closure C[i, j] = true iff i ⇒ j. C stands for connectivity or reachability matrix; C = A∗ is also called transitive hull or transitive closure, since it is the smallest transitive relation that "encloses" E. Exhibit 11.1: Example of a directed graph with its adjacency and connectivity matrix. (Undirected) graph. If the relation E ⊆ N ξ N is symmetric [i.e. for every ordered pair (i, j) of nodes it also contains the opposite pair (j, i)] we can identify the two arcs (i, j) and (j, i) with a single edge, the unordered pair (i, j). Books on graph theory typically start with the definition of undirected graphs (graphs, for short), but we treat them as a special case of directed graphs because the latter occur much more often in computer science. Whereas graphs are based on the concept of an edge between two nodes, directed graphs embody the concept of one-way arcs leading from a node to another one. Boolean matrix multiplication Let A, B, C be n ξ n boolean matrices defined by type nnboolean: array[1 .. n, 1 .. n] of boolean; var A, B, C: nnboolean; The boolean matrix multiplication C = A · B is defined as and implemented by and implemented by procedure mmb(var a, b, c: nnboolean); var i, j, k: integer; begin for i := 1 to n do for j := 1 to n do begin c[i, j] := false; for k := 1 to n do c[i, j] := c[i, j] or (a[i, k] and b[k, j]) (∗) end end; Remark: Remember (in the section, “Pascal and its dialects: Lingua franca of computer science”) that we usually assume the boolean operations 'or' and 'and' to be conditional (i.e. their arguments are evaluated only as far as necessary to determine the value of the expression). An extension of this simple idea leads to an alternative way of coding boolean matrix multiplication that speeds up the innermost loop above for large values of n. Explain why the following code is equivalent to (∗∗): k:=1; 94 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 T T T T T T T T T T T T T T T T T T T T T C 1 2 3 4 5 1 2 3 4 5 T T T T T T A | algorithms and data structures_Page_94_Chunk4634 |
This book is licensed under a Creative Commons Attribution 3.0 License while not c[i, j] and (k ≤ n) do { c[i, j] := a[i, k] and b[k, j]; k := k + 1 } Multiplication also defines powers, and this gives us a first solution to the problem of computing the transitive closure. If Al+1 denotes the L-th power of A, the formula has a clear interpretation: There exists a path of length L + 1 from i to j iff, for some node k, there exists a path of length L from i to k and a path of length 1 (a single arc) from k to j. Thus A2 represents all paths of length 2; in general, AL represents all paths of length L, for L ≥ 1: AL[i, j] = true iff there exists a path of length L from i to j. Rather than dealing directly with the adjacency matrix A, it is more convenient to construct the matrix A' = A or I. The identity matrix I has the values 'true' along the diagonal, 'false' everywhere else. Thus in A' all diagonal elements A'[i, i] = true. Then A'L describes all paths of length ≤ L (instead of exactly equal to L), for L ≥ 0. Therefore, the transitive closure is A∗ = A'(n-1) The efficiency of an algorithm is often measured by the number of "elementary" operations that are executed on a given data set. The execution time of an elementary operation [e.g. the binary boolean operators (and, or) used above] does not depend on the operands. To estimate the number of elementary operations performed in boolean matrix multiplication as a function of the matrix size n, we concentrate on the leading terms and neglect the lesser terms. Let us use asymptotic notation in an intuitive way; it is defined formally in Part IV. The number of operations (and, or), executed by procedure 'mmb' when multiplying two boolean n ξ n matrices is Θ(n3) since each of the nested loops is iterated n times. Hence the cost for computing A'(n–1) by repeatedly multiplying with A' is Θ(n4). This algorithm can be improved to Θ(n3 · log n) by repeatedly squaring: A'2, A'4, A'8 , … , A'k where k is the smallest power of 2 with k ≥ n – 1. It is not necessary to compute exactly A'(n–1). Instead of A'13, for example, it suffices to compute A'16, the next higher power of 2, which contains all paths of length at most 16. In a graph with 14 nodes, this set is equal to the set of all paths of length at most 1. Warshall's algorithm In search of a faster algorithm we consider other ways of iterating over the set of all paths. Instead of iterating over paths of growing length, we iterate over an increasing number of nodes that may be used along a path from node i to node j. This idea leads to an elegant algorithm due to Warshall [War 62]: Compute a sequence of matrices B0, B1, B2, … , Bn: B0[i, j] = A'[i, j] = true iff i = j or i → j. B1[i, j] = true iff i ⇒ j using at most node 1 along the way. B2[i, j] = true iff i ⇒ j using at most nodes 1 and 2 along the way … Bk[i, j] = true iff i ⇒ j using at most nodes 1, 2, … , k along the way. The matrices B0, B1, … express the existence of paths that may touch an increasing number of nodes along the way from node i to node j; thus Bn talks about unrestricted paths and is the connectivity matrix C = Bn. An iteration step Bk–1 → Bk is computed by the formula Algorithms and Data Structures 95 A Global Text | algorithms and data structures_Page_95_Chunk4635 |
11. Matrices and graphs: transitive closure Bk[i, j] = Bk–1[i, j] or (Bk–1[i, k] and Bk–1[k, j]). The cost for performing one step is Θ(n2), the cost for computing the connectivity matrix is therefore Θ(n3). A comparison of the formula for Warshall's algorithm with the formula for matrix multiplication shows that the n-ary 'OR' has been replaced by a binary 'or'. At first sight, the following procedure appears to execute the algorithm specified above, but a closer look reveals that it executes something else: the assignment in the innermost loop computes new values that are used immediately, instead of the old ones. procedure warshall(var a: nnboolean); var i, j, k: integer; begin for k := 1 to n do for i := 1 to n do for j := 1 to n do a[i, j] := a[i, j] or (a[i, k] and a[k, j]) { this assignment mixes values of the old and new matrix } end; A more thorough examination, however, shows that this "naively" programmed procedure computes the correct result in-place more efficiently than would direct application of the formulas for the matrices Bk. We encourage you to verify that the replacement of old values by new ones leaves intact all values needed for later steps; that is, show that the following equalities hold: Bk[i, k] = Bk–1[i, k] and Bk[k, j] = Bk–1[k, j]. Exercise: distances in a directed graph, Floyd's algorithm Modify Warshall's algorithm so that it computes the shortest distance between any pair of nodes in a directed graph where each arc is assigned a length ≥ 0. We assume that the data is given in an n ξ n array of reals, where d[i, j] is the length of the arc between node i and node j. If no arc exists, then d[i, j] is set to ∞, a constant that is the largest real number that can be represented on the given computer. Write a procedure 'dist' that works on an array d of type type nnreal = array[1 .. n, 1 .. n] of real; Think of the meaning of the boolean operations 'and' and 'or' in Warshall's algorithm, and find arithmetic operations that play an analogous role for the problem of computing distances. Explain your reasoning in words and pictures. Solution The following procedure 'dist' implements Floyd's algorithm [Flo 62]. We assume that the length of a nonexistent arc is ∞, that x + ∞ = ∞, and that min(x, ∞) = x for all x. procedure dist(var d: nnreal); var i, j, k: integer; begin for k := 1 to n do for i := 1 to n do for j := 1 to n do d[i, j] := min(d[i, j], d[i, k] + d[k, j]) end; 96 | algorithms and data structures_Page_96_Chunk4636 |
This book is licensed under a Creative Commons Attribution 3.0 License Exercise: shortest paths In addition to the distance d[i, j] of the preceding exercise, we wish to compute a shortest path from i to j (i.e. one that realizes this distance). Extend the solution above and write a procedure 'shortestpath' that returns its result in an array 'next' of type: type nnn = array[1 .. n, 1 .. n] of 0 .. n; next[i,j] contains the next node after i on a shortest path from i to j, or 0 if no such path exists. Solution procedure shortestpath(var d: nnreal; var next: nnn); var i, j, k: integer; begin for i := 1 to n do for j := 1 to n do if d[i, j] ≠ ∞ then next[i, j] := j else next[i, j] := 0; for k := 1 to n do for i := 1 to n do for j := 1 to n do if d[i, k] + d[k, j] < d[i, j] then { d[i, j] := d[i, k] + d[k, j]; next[i, j] := next[i, k] } end; It is easy to prove that next[i, j] = 0 at the end of the algorithm iff d[i, j] = ∞ (i.e. there is no path from i to j). Minimum spanning tree in a graph Consider a weighted graph G = (V, E, w), where V = {v1, …, vn} is the set of vertices, E = {e1, … , em} is the set of edges, each edge ei is an unordered pair (vj, vk) of vertices, and w: E → R assigns a real number to each edge, which we call its weight. We consider only connected graphs G, in the sense that any pair (vj, vk) of vertices is connected by a sequence of edges. In the following example, the edges are labeled with their weight (Exhibit 11.2). Exhibit 11.2: Example of a minimum spanning tree. A tree T is a connected graph that contains no circuits: any pair (vj, vk) of vertices in T is connected by a unique sequence of edges. A spanning tree of a graph G is a subgraph T of G, given by its set of edges ET ⊆ E, that is a tree and satisfies the additional condition of being maximal, in the sense that no edge in E \ E T can be added to T without destroying the tree property. Observation: a connected graph G has at least one spanning tree. The weight Algorithms and Data Structures 97 A Global Text | algorithms and data structures_Page_97_Chunk4637 |
11. Matrices and graphs: transitive closure of a spanning tree is the sum of the weights of all its edges. A minimum spanning tree is a spanning tree of minimal weight. In Exhibit 11.2, the bold edges form the minimal spanning tree. Consider the following two algorithms: Grow: ET := ∅; { initialize to empty set } while T is not a spanning tree do ET := ET ∪ {a min cost edge that does not form a circuit when added to ET} Shrink: ET := E; { initialize to set of all edges } while T is not a spanning tree do ET := ET \ {a max cost edge that leaves T connected after its removal} Claim: The "growing algorithm" and "shrinking algorithm" determine a minimum spanning tree. If T is a spanning tree of G and e = (vj, vk) ∉ ET, we define Ckt(e, T), "the circuit formed by adding e to T" as the set of edges in ET that form a path from vj to vk. In the example of Exhibit 11.2 with the spanning tree shown in bold edges we obtain Ckt((v4, v5), T) = {(v4, v1), (v1, v2), (v2, v5)}. Exercise Show that for each edge e ∉ ET there exists exactly one such circuit. Show that for any e ∉ ET and any t ∉ Ckt(e, T) the graph formed by (ET \ {t}) ∪ {e} is still a spanning tree. A local minimum spanning tree of G is a spanning tree T with the property that there exist no two edges e ∉ ET , t ∉ Ckt(e, T) with w(e) < w(t). Consider the following 'exchange algorithm', which computes a local minimum spanning tree: Exchange: T := any spanning tree; while there exists e ∉ ET, t ∈ Ckt(e, T) with w(e) < w(t) do ET := (ET \ {t}) ∪ {e}; { exchange } Theorem: A local minimum spanning tree for a graph G is a minimum spanning tree. For the proof of this theorem we need: Lemma: If T' and T" are arbitrary spanning trees for G, T' ≠ T", then there exist e" ∉ ET' , e' ∉ ET" , such that e" ∈ Ckt(e', T") and e' ∈ Ckt(e", T'). Proof: Since T' and T" are spanning trees for G and T' ≠ T", there exists e" ∈ ET" \ ET'. Assume that Ckt(e", T') ⊆T". Then e" and the edges in Ckt(e", T') form a circuit in T" that contradicts the assumption that T" is a tree. Hence there must be at least one e' ∈ Ckt(e", T') \ ET". Assume that for all e' ∈ Ckt(e", T') \ ET" we have e" ∈ Ckt(e', T"). Then forms a circuit in T" that contradicts the proposition that T" is a tree. Hence there must be at least one e' ∈ Ckt(e", T') \ ET" with e" ∈ Ckt(e', T"). 98 | algorithms and data structures_Page_98_Chunk4638 |
This book is licensed under a Creative Commons Attribution 3.0 License Proof of the Theorem: Assume that T' is a local minimum spanning tree. Let T" be a minimum spanning tree. If T' ≠ T" the lemma implies the existence of e' ∈ Ckt(e", T') \ ET" and e" ∈ Ckt(e', T") \ ET'. If w(e') < w(e"), the graph defined by the edges (ET" \ {e"}) ∪ {e'} is a spanning tree with lower weight than T". Since T" is a minimum spanning tree, this is impossible and it follows that w(e') ≥w (e"). (∗) If w(e') > w(e"), the graph defined by the edges (ET' \ {e'}) ∪ {e"} is a spanning tree with lower weight than T'. Since T" is a local minimum spanning tree, this is impossible and it follows that w(e') ≤ w(e"). (∗∗) From (∗) and (∗∗) it follows that w(e') = w(e") must hold. The graph defined by the edges (E T" \ {e"}) ∪ {e'} is still a spanning tree that has the same weight as T". We replace T" by this new minimum spanning tree and continue the replacement process. Since T' and T" have only finitely many edges the process will terminate and T" will become equal to T'. This proves that T" is a minimum spanning tree. The theorem implies that the tree computed by 'Exchange' is a minimum spanning tree. Exercises 1. Consider how to extend the transitive closure algorithm based on boolean matrix multiplication so that it computes (a) distances and (b) a shortest path. 2. Prove that the algorithms 'Grow' and 'Shrink' compute local minimum spanning trees. Thus they are minimum spanning trees by the theorem of the section entitled “Minimum spanning tree in a graph”. Algorithms and Data Structures 99 A Global Text | algorithms and data structures_Page_99_Chunk4639 |
This book is licensed under a Creative Commons Attribution 3.0 License 12. Integers Learning objectives: • integers and their operations • Euclidean algorithm • Sieve of Eratosthenes • large integers • modular arithmetic • Chinese remainder theorem • random numbers and their generators Operations on integers Five basic operations account for the lion's share of integer arithmetic: + – · div mod The product 'x · y', the quotient 'x div y', and the remainder 'x mod y' are related through the following div-mod identity: (1) (x div y) · y + (x mod y) = x for y ≠ 0. Many programming languages provide these five operations, but unfortunately, 'mod' tends to behave differently not only between different languages but also between different implementations of the same language. How come have we not learned in school what the remainder of a division is? The div-mod identity, a cornerstone of number theory, defines 'mod' assuming that all the other operations are defined. It is mostly used in the context of nonnegative integers x ≥ 0, y > 0, where everything is clear, in particular the convention 0 ≤ x mod y < y. One half of the domain of integers consists of negative numbers, and there are good reasons for extending all five basic operations to the domain of all integers (with the possible exception of y = 0), such as: • Any operation with an undefined result hinders the portability and testing of programs: if the "forbidden" operation does get executed by mistake, the computation may get into nonrepeatable states. Example: from a practical point of view it is better not to leave 'x div 0' undefined, as is customary in mathematics, but to define the result as '= overflow', a feature typically supported in hardware. • Some algorithms that we usually consider in the context of nonnegative integers have natural extensions into the domain of all integers (see the following sections on 'gcd' and modular number representations). Unfortunately, the attempt to extend 'mod' to the domain of integers runs into the problem mentioned above: How should we define 'div' and 'mod'? Let's follow the standard mathematical approach of listing desirable properties these operations might possess. In addition to the "sacred" div-mod identity (1) we consider: (2) Symmetry of div: (–x) div y = x div (–y) = –(x div y). The most plausible way to extend 'div' to negative numbers. Algorithms and Data Structures 100 A Global Text | algorithms and data structures_Page_100_Chunk4640 |
12. Integers (3) A constraint on the possible values assumed by 'x mod y', which, for y > 0, reduces to the convention of nonnegative remainders: 0 ≤ x mod y < y. This is important because a standard use of 'mod' is to partition the set of integers into y residue classes. We consider a weak and a strict requirement: (3') Number of residue classes = |y|: for given y and varying x, 'x mod y' assumes exactly |y| distinct values. (3") In addition, we ask for nonnegative remainders: 0 ≤ x mod y < |y|. Pondering the consequences of these desiderata, we soon realize that 'div' cannot be extended to negative arguments by means of symmetry. Even the relatively innocuous case of positive denominator y > 0 makes it impossible to preserve both (2) and (3"), as the following failed attempt shows: ((–3) div 2) · 2 + ((–3) mod 2) ?=? –3 Preserving (1) (–(3 div 2)) · 2 + 1 ?=? –3 and using (2) and (3") (–1) · 2 + 1 ≠–3 … fails! Even the weak condition (3'), which we consider essential, is incompatible with (2). For y = –2, it follows from (1) and (2) that there are three residue classes modulo (–2): x mod (–2) yields the values 1, 0, –1; for example, 1 mod (–2) = 1, 0 mod (–2) = 0, (–1) mod (–2) = –1. This does not go with the fact that 'x mod 2' assumes only the two values 0, 1. Since a reasonable partition into residue classes is more important than the superficially appealing symmetry of 'div', we have to admit that (2) was just wishful thinking. Without giving any reasons, [Knu 73a] (see the chapter "Reducing a task to given primitives; programming motion) defines 'mod' by means of the div-mod identity (1) as follows: x mod y = x – y · x / y, if y ≠ 0; x mod 0 = x; Thus he implicitly defines x div y = x / y, where z, the "floor" of z, denotes the largest integer ≤ z; the "ceiling" z denotes the smallest integer ≥ z. Knuth extends the domain of 'mod' even further by defining "x mod 0 = x". With the exception of this special case y = 0, Knuth's definition satisfies (3'): Number of residue classes = |y|. The definition does not satisfy (3"), but a slightly more complicated condition. For given y ≠ 0, we have 0 ≤ x mod y < y, if y > 0; and 0 ≥ x mod y > y, if y < 0. Knuth's definition of 'div' and 'mod' has the added advantage that it holds for real numbers as well, where 'mod' is a useful operation for expressing the periodic behavior of functions [e.g. tan x = tan (x mod π)]. Exercise: another definition of 'div' and 'mod' 1. Show that the definition in conjunction with the div-mod identity (1) meets the strict requirement (3"). 101 | algorithms and data structures_Page_101_Chunk4641 |
This book is licensed under a Creative Commons Attribution 3.0 License Solution Exercise Fill out comparable tables of values for Knuth's definition of 'div' and 'mod'. Solution The Euclidean algorithm A famous algorithm for computing the greatest common divisor (gcd) of two natural numbers appears in Book 7 of Euclid's Elements (ca. 300 BC). It is based on the identity gcd(u, v) = gcd(u – v, v), which can be used for u > v to reduce the size of the arguments, until the smaller one becomes 0. We use these properties of the greatest common divisor of two integers u and v > 0: gcd(u, 0) = u By convention this also holds for u = 0. gcd(u, v) = gcd(v, u) Permutation of arguments, important for the termination of the following procedure. gcd(u, v) = gcd(v, u – q · v) For any integer q. The formulas above translate directly into a recursive procedure: Algorithms and Data Structures 102 A Global Text | algorithms and data structures_Page_102_Chunk4642 |
12. Integers function gcd(u, v: integer): integer; begin if v = 0 then return(u) else return(gcd(v, u mod v)) end; A test for the relative size of u and v is unnecessary. If initially u < v, the first recursive call permutes the two arguments, and thereafter the first argument is always larger than the second. This simple and concise solution has a relatively high implementation cost. A stack, introduced to manage the recursive procedure calls, consumes space and time. In addition to the operations visible in the code (test for equality, assignment, and 'mod'), hidden stack maintenance operations are executed. There is an equally concise iterative version that requires a bit more thinking and writing, but is significantly more efficient: function gcd(u, v: integer): integer; var r: integer; begin while v ≠ 0 do { r := u mod v; u := v; v := r }; return(u) end; The prime number sieve of Eratosthenes The oldest and best-known algorithm of type sieve is named after Eratosthenes (ca. 200 BC). A set of elements is to be separated into two classes, the "good" ones and the "bad" ones. As is often the case in life, bad elements are easier to find than good ones. A sieve process successively eliminates elements that have been recognized as bad; each element eliminated helps in identifying further bad elements. Those elements that survive the epidemic must be good. Sieve algorithms are often applicable when there is a striking asymmetry in the complexity or length of the proofs of the two assertions "p is a good element" and "p is a bad element". This theme occurs prominently in the complexity theory of problems that appear to admit only algorithms whose time requirement grows faster than polynomially in the size of the input (NP completeness). Let us illustrate this asymmetry in the case of prime numbers, for which Eratosthenes' sieve is designed. In this analogy, "prime" is "good" and "nonprime" is "bad". A prime is a positive integer greater than 1 that is divisible only by 1 and itself. Thus primes are defined in terms of their lack of an easily verified property: a prime has no factors other than the two trivial ones. To prove that 1 675 307 419 is not prime, it suffices to exhibit a pair of factors: 1 675 307 419 = 1 234 567 · 1 357. This verification can be done by hand. The proof that 217 – 1 is prime, on the other hand, is much more elaborate. In general (without knowledge of any special property this particular number might have) one has to verify, for each and every number that qualifies as a candidate factor, that it is not a factor. This is obviously more time consuming than a mere multiplication. Exhibiting factors through multiplication is an example of what is sometimes called a "one-way" or "trapdoor" function: the function is easy to evaluate (just one multiplication), but its inverse is hard. In this context, the inverse of multiplication is not division, but rather factorization. Much of modern cryptography relies on the difficulty of factorization. The prime number sieve of Eratosthenes works as follows. We mark the smallest prime, 2, and erase all of its multiples within the desired range 1 .. n. The smallest remaining number must be prime; we mark it and erase its 103 | algorithms and data structures_Page_103_Chunk4643 |
This book is licensed under a Creative Commons Attribution 3.0 License multiples. We repeat this process for all numbers up to √n: If an integer c < n can be factored, c = a · b, then at least one of the factors is <√n. { sieve of Eratosthenes marks all the primes in 1 .. n } const n = … ; var sieve: packed array [2 .. n] of boolean; p, sqrtn, i: integer; … begin for i := 2 to n do sieve[i] := true; { initialize the sieve } sqrtn := trunc(sqrt(n)); { it suffices to consider as divisors the numbers up to √n } p := 2; while p ≤ sqrtn do begin i := p · p; while i ≤ n do { sieve[i] := false; i := i + p }; repeat p := p + 1 until sieve[p]; end; end; Large integers The range of numbers that can be represented directly in hardware is typically limited by the word length of the computer. For example, many small computers have a word length of 16 bits and thus limit integers to the range – 215 ≤ a < +215 =32768. When the built-in number system is insufficient, a variety of software techniques are used to extend its range. They differ greatly with respect to their properties and intended applications, but all of them come at an additional cost in memory and, above all, in the time required for performing arithmetic operations. Let us mention the most common techniques. Double-length or double-precision integers. Two words are used to hold an integer that squares the available range as compared to integers stored in one word. For a 16-bit computer we get 32-bit integers, for a 32- bit computer we get 64-bit integers. Operations on double-precision integers are typically slower by a factor of 2 to 4. Variable precision integers. The idea above is extended to allocate as many words as necessary to hold a given integer. This technique is used when the size of intermediate results that arise during the course of a computation is unpredictable. It calls for list processing techniques to manage memory. The time of an operation depends on the size of its arguments: linearly for addition, mostly quadratically for multiplication. Packed BCD integers. This is a compromise between double precision and variable precision that comes from commercial data processing. The programmer defines the maximal size of every integer variable used, typically by giving the maximal number of decimal digits that may be needed to express it. The compiler allocates an array of bytes to this variable that contains the following information: maximal length, current length, sign, and the digits. The latter are stored in BCD (binary-coded decimal) representation: a decimal digit is coded in 4 bits, two of them are packed into a byte. Packed BCD integers are expensive in space because most of the time there is unused allocated space; and even more so in time, due to digit-by-digit arithmetic. They are unsuitable for lengthy scientific/technical computations, but OK for I/O-intensive data processing applications. Algorithms and Data Structures 104 A Global Text | algorithms and data structures_Page_104_Chunk4644 |
12. Integers Modular number systems: the poor man's large integers Modular arithmetic is a special-purpose technique with a narrow range of applications, but is extremely efficient where it applies—typically in combinatorial and number-theoretic problems. It handles addition, and particularly multiplication, with unequaled efficiency, but lacks equally efficient algorithms for division and comparison. Certain combinatorial problems that require high precision can be solved without divisions and with few comparisons; for these, modular numbers are unbeatable. Chinese Remainder Theorem: Let m1, m2, … , mk be pairwise relatively prime positive integers, called moduli. Let m = m1 · m2 · … · mk be their product. Given k positive integers r1, r2, … , rk, called residues, with 0 ≤ ri < mi for 1 ≤ i ≤ rk, there exists exactly one integer r, 0 ≤ r < m, such that r mod m i = ri for 1 ≤ i ≤ k. The Chinese remainder theorem is used to represent integers in the range 0 ≤ r < m uniquely as k-tuples of their residues modulo mi. We denote this number representation by r ~ [r1, r2, … , rk]. The practicality of modular number systems is based on the following fact: The arithmetic operations (+ , – , ·) on integers r in the range 0 ≤ r< m are represented by the same operations, applied componentwise to k-tuples [r 1, r2, … , rk]. A modular number system replaces a single +, –, or · in a large range by k operations of the same type in small ranges. If r ~ [r1, r2, … , rk], s ~ [s1, s2, … , sk], t ~ [t1, t2, … , tk], then: (r + s)mod m = t ⇔(ri + si) mod mi = ti for 1 ≤ i ≤ k, (r – s)mod m = t ⇔(ri – si) mod mi = ti for 1 ≤ i ≤ k, (r · s)mod m = t ⇔(ri · si) mod mi = ti for 1 ≤ i ≤ k. Example m1 = 2 and m2 = 5, hence m = m1 · m2 = 2 · 5 = 10. In the following table the numbers r in the range 0 .. 9 are represented as pairs modulo 2 and modulo 5. Let r = 2 and s = 3, hence r · s = 6. In modular representation: r ~ [0, 2], s ~ [1, 3], hence r · s ~ [0, 1]. A useful modular number system is formed by the moduli m1 = 99, m2 = 100, m3 = 101, hence m = m1 · m2 · m3 = 999900. Nearly a million integers in the range 0 ≤ r < 999900 can be represented. The conversion of a decimal number to its modular form is easily computed by hand by adding and subtracting pairs of digits as follows: r mod 99: Add pairs of digits, and take the resulting sum mod 99. r mod 100: Take the least significant pair of digits. r mod 101: Alternatingly add and subtract pairs of digits, and take the result mod 101. The largest integer produced by operations on components is 1002 ~ 213; it is smaller than 215 = 32768 ~ 32k and thus causes no overflow on a computer with 16-bit arithmetic. 105 | algorithms and data structures_Page_105_Chunk4645 |
This book is licensed under a Creative Commons Attribution 3.0 License Example r = 123456 r mod 99 = (56 + 34 + 12) mod 99 = 3 r mod 100 = 56 r mod 101 = (56 – 34 + 12) mod 101 = 34 r ~ [3, 56, 34] s = 654321 s mod 99 = (21 + 43 + 65) mod 99 = 30 s mod 100 = 21 s mod 101 = (21 – 43 + 65) mod 101 = 43 s ~ [30, 21, 43] r + s ~ [3, 56, 34] + [30, 21, 43] = [33, 77, 77] Modular arithmetic has some shortcomings: division, comparison, overflow detection, and conversion to decimal notation trigger intricate computations. Exercise: Fibonacci numbers and modular arithmetic The sequence of Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, … is defined by x0 = 0, x1 = 1, xn = xn–1 + xn–2 for n ≥ 2. Write (a) a recursive function (b) an iterative function that computes the n-th element of this sequence. Using modular arithmetic, compute Fibonacci numbers up to 108 on a computer with 16-bit integer arithmetic, where the largest integer is 215 – 1 = 32767. (c) Using moduli m1 = 999, m2 = 1000, m3 = 1001, what is the range of the integers that can be represented uniquely by their residues [r1, r2, r3] with respect to these moduli? (d) Describe in words and formulas how to compute the triple [r1, r2, r3] that uniquely represents a number r in this range. (e) Modify the function in (b) to compute Fibonacci numbers in modular arithmetic with the moduli 999, 1000, and 1001. Use the declaration type triple = array [1 .. 3] of integer; and write the procedure procedure modfib(n: integer; var r: triple); Solution (a) function fib(n: integer): integer; begin if n ≤ 1 then return(n) else return(fib(n – 1) + fib(n – 2)) end; (b) function fib(n: integer): integer; var p, q, r, i: integer; begin if n ≤ 1 then return(n) Algorithms and Data Structures 106 A Global Text | algorithms and data structures_Page_106_Chunk4646 |
12. Integers else begin p := 0; q := 1; for i := 2 to n do { r := p + q; p := q; q := r }; return(r) end end; (c) The range is 0 .. m – 1 with m = m1 · m2 · m3 = 999 999 000. (d) r = d1 · 1 000 000 + d2 · 1000 + d3 with 0 ≤ d1, d2, d3 ≤ 999 1 000 000 = 999 999 + 1= 1001 · 999 + 1 1000 = 999 + 1 = 1001 – 1 r1 = r mod 999 = (d1 + d2 + d3) mod 999 r2 = r mod 1000 = d3 r3 = r mod 1001 = (d1 – d2 + d3) mod 1001 (e) procedure modfib(n: integer; var r: triple); var p, q: triple; i, j: integer; begin if n ≤ 1 then for j := 1 to 3 do r[j] := n else begin for j := 1 to 3 do { p[j] := 0; q[j] := 1 }; for i := 2 to n do begin for j := 1 to 3 do r [j] := (p[j] + q[j]) mod (998 + j); p := q; q := r end end end; Random numbers The colloquial meaning of the term at random often implies "unpredictable". But random numbers are used in scientific/technical computing in situations where unpredictability is neither required nor desirable. What is needed in simulation, in sampling, and in the generation of test data is not unpredictability but certain statistical properties. A random number generator is a program that generates a sequence of numbers that passes a number of specified statistical tests. Additional requirements include: it runs fast and uses little memory; it is portable to computers that use a different arithmetic; the sequence of random numbers generated can be reproduced (so that a test run can be repeated under the same conditions). In practice, random numbers are generated by simple formulas. The most widely used class, linear congruential generators, given by the formula ri+1 = (a · ri + c) mod m are characterized by three integer constants: the multiplier a, the increment c, and the modulus m. The sequence is initialized with a seed r0. All these constants must be chosen carefully. Consider, as a bad example, a formula designed to generate random days in the month of February: r0 = 0, ri+1 = (2 · ri + 1) mod 28. It generates the sequence 0, 1, 3, 7, 15, 3, 7, 15, 3, … . Since 0 ≤ ri < m, each generator of the form above generates a sequence with a prefix of length < m which is followed by a period of length ≤ m. In the example, the 107 | algorithms and data structures_Page_107_Chunk4647 |
This book is licensed under a Creative Commons Attribution 3.0 License prefix 0, 1 of length 2 is followed by a period 3, 7, 15 of length 3. Usually we want a long period. Results from number theory assert that a period of length m is obtained if the following conditions are met: • m is chosen as a prime number. • (a – 1) is a multiple of m. • m does not divide c. Example r0 = 0, ri+1 = (8 · ri + 1) mod 7 generates a sequence: 0, 1, 2, 3, 4, 5, 6, 0, … with a period of length 7. Shall we accept this as a sequence of random integers, and if not, why not? Should we prefer the sequence 4, 1, 6, 2, 3, 0, 5, 4, … ? For each application of random numbers, the programmer/analyst has to identify the important statistical properties required. Under normal circumstances these include: No periodicity over the length of the sequence actually used. Example: to generate a sequence of 100 random weekdays ∈ {Su, Mo, … , Sat}, do not pick a generator with modulus 7, which can generate a period of length at most 7; pick one with a period much longer than 100. A desired distribution, most often the uniform distribution. If the range 0 .. m – 1 is partitioned into k equally sized intervals I1, I2, … , Ik, the numbers generated should be uniformly distributed among these intervals; this must be the case not only at the end of the period (this is trivially so for a generator with maximal period m), but for any initial part of the sequence. Many well-known statistical tests are used to check the quality of random number generators. The run test (the lengths of monotonically increasing and monotonically decreasing subsequences must occur with the right frequencies); the gap test (given a test interval called the "gap", how many consecutively generated numbers fall outside?); the permutation test (partition the sequence into subsequences of t elements; there are t! possible relative orderings of elements within a subsequence; each of these orderings should occur about equally often). Exercise: visualization of random numbers Write a program that lets its user enter the constants a, c, m, and the seed r0 for a linear congruential generator, then displays the numbers generated as dots on the screen: A pair of consecutive random numbers is interpreted as the (x, y)-coordinates of the dot. You will observe that most generators you enter have obvious flaws: our visual system is an excellent detector of regular patterns, and most regularities correspond to undesirable statistical properties. The point made above is substantiated in [PM 88]. The following simple random number generator and some of its properties are easily memorized: r0 = 1, ri+1 = 125 · ri mod 8192. 1. 8192 = 213, hence the remainder mod 8192 is represented by the 13 least significant bits. 2. 125 = 127 – 2 = (1111101) in binary representation. 3. Arithmetic can be done with 16-bit integers without overflow and without regard to the representation of negative numbers. Algorithms and Data Structures 108 A Global Text | algorithms and data structures_Page_108_Chunk4648 |
12. Integers 4. The numbers rk generated are exactly those in the range 0 ≤ rk < 8192 with rk mod 4 = 1 (i.e. the period has length 211 = 2048). 5. Its statistical properties are described in [Kru 69], [Knu 81] contains the most comprehensive treatment of the theory of random number generators. As a conclusion of this brief introduction, remember an important rule of thumb: Never choose a random number generator at random! Exercises 1. Work out the details of implementing double-precision, variable-precision, and BCD integer arithmetic, and estimate the time required for each operation as compared to the time of the same operation in single precision. For variable precision and BCD, introduce the length L of the representation as a parameter. 2. The least common multiple (lcm) of two integers u and v is the smallest integer that is a multiple of u and v. Design an algorithm to compute lcm(u, v). 3. The prime decomposition of a natural number n > 0 is the (unique) multiset PD(n) = [p1, p2, … , pk] of primes pi whose product is n. A multiset differs from a set in that elements may occur repeatedly (e.g. PD(12) = [2, 2, 3]). Design an algorithm to compute PD(n) for a given n > 0. 4. Work out the details of modular arithmetic with moduli 9, 10, 11. 5. Among the 95 linear congruential random number generators given by the formula ri+1 = a · ri mod m, with prime modulus m = 97 and 1 < a < 97, find out how many get disqualified "at first sight" by a simple visual test. Consider that the period of these RNGs is at most 97. 109 | algorithms and data structures_Page_109_Chunk4649 |
This book is licensed under a Creative Commons Attribution 3.0 License 13. Reals Learning objectives: • floating-point numbers and their properties • pitfalls of numeric computation • Horner's method • bisection • Newton's method Floating-point numbers Real numbers, those declared to be of type REAL in a programming language, are represented as floating-point numbers on most computers. A floating-point number z is represented by a (signed) mantissa m and a (signed) exponent e with respect to a base b: z=± m·b±e (e.g. z=+0.11·2–1). This section presents a very brief introduction to floating-point arithmetic. We recommend [Gol91] as a comprehensive survey. Floating-point numbers can only approximate real numbers, and in important ways, they behave differently. The major difference is due to the fact that any floating-point number system is a finite number system, as the mantissa m and the exponent e lie in a bounded range. Consider, as a simple example, the following number system: z = ±0.b1b2 · 2±e, where b1, b2, and e may take the values 0 and 1. The number representation is not unique: The same real number may have many different representations, arranged in the following table by numerical value (lines) and constant exponent (columns). 1.5 + 0.11 · 2+1 1.0 + 0.10 · 2+1 0.75 + 0.11 · 2±0 0.5 + 0.01 · 2+1 + 0.10 · 2±0 0.375 +0.11 · 2–1 0.25 + 0.01 · 2±0 +0.10 · 2–1 0.125 +0.01 · 2–1 0. +0.00 · 2+1 + 0.00 · 2±0 +0.00 · 2–1 The table is symmetric for negative numbers. Notice the cluster of representable numbers around zero. There are only 15 different numbers, but 25= 32 different representations. Exercise: a floating-point number system Consider floating-point numbers represented in a 6-bit "word" as follows: The four bits b b2 b1 b0 represent a signed mantissa, the two bits e e0 a signed exponent to the base 2. Every number has the form x=b b2 b1 b0·2 ee0. Algorithms and Data Structures 110 A Global Text | algorithms and data structures_Page_110_Chunk4650 |
13. Reals Both the exponent and the mantissa are integers represented in 2's complement form. This means that the integer values –2..1 are assigned to the four different representations e e0 as shown: v e e0 0 0 0 1 0 1 –2 1 0 –1 1 1 1. Complete the following table of the values of the mantissa and their representation, and write down a formula to compute v from b b2 b1 b0. v b b2 b1 b0 0 0 0 0 0 1 0 0 0 1 … 7 0 1 1 1 –8 1 0 0 0 … –1 1 1 1 1 2. How many different number representations are there in this floating-point system? 3. How many different numbers are there in this system? Draw all of them on an axis, each number with all its representations. On a byte-oriented machine, floating-point numbers are often represented by 4 bytes =32 bits: 24 bits for the signed mantissa, 8 bits for the signed exponent. The mantissa m is often interpreted as a fraction 0 ≤ m < 1, whose precision is bounded by 23 bits; the 8-bit exponent permits scaling within the range 2–128 ≤ 2e ≤ 2127. Because 32- and 64-bit floating-point number systems are so common, often coexisting on the same hardware, these number systems are often identified with "single precision" and "double precision", respectively. In recent years an IEEE standard format for-single precision floating-point numbers has emerged, along with standards for higher precisions: double, single extended, and double extended. 111 | algorithms and data structures_Page_111_Chunk4651 |
This book is licensed under a Creative Commons Attribution 3.0 License The following example shows the representation of the number +1.011110 … 0 · 2–54 in the IEEE format: Some dangers Floating-point computation is fraught with problems that are hard to analyze and control. Unexpected results abound, as the following examples show. The first two use a binary floating-point number system with a signed 2- bit mantissa and a signed 1-bit exponent. Representable numbers lie in the range –0.11 · 2+1 ≤ z ≤ +0.11 · 2+1. Example: y + x = y and x ≠ 0 It suffices to choose |x| small as compared to |y|; for example, x = 0.01 · 2–1, y = 0.10 · 2+1. The addition forces the mantissa of x to be shifted to the right until the exponents are equal (i.e. x is represented as 0.0001·2+1). Even if the sum is computed correctly as 0.1001 ·2+1 in an accumulator of double length, storing the result in memory will force rounding: x + y=0.10·2+1=y. Example: Addition is not associative: (x + y) + z ≠ x + (y + z) The following values for x, y, and z assign different values to the left and right sides. Left side: (0.10 · 2+1 + 0.10 · 2–1) + 0.10 · 2–1 = 0.10 · 2+1 Right side: 0.10 · 2+1 + (0.10 · 2–1 + 0.10 · 2–1) = 0.11 · 2+1 A useful rule of thumb helps prevent the loss of significant digits: Add the small numbers before adding the large ones. Example: ((x + y)2 – x2 – 2xy) / y2 = 1? Let's evaluate this expression for large |x| and small |y| in a floating-point number system with five decimal digits. x = 100.00, y = .01000 x + y = 100.01 (x + y)2 = 10002.0001, rounded to five digits yields 10002. x2 = 10000. (x + y)2 – x2 = 2.???? (four digits have been lost!) 2xy = 2.0000 (x + y)2 – x2 – 2xy = 2.???? – 2.0000 = 0.????? Now five digits have been lost, and the result is meaningless. Example: numerical instability Recurrence relations for sequences of numbers are prone to the phenomenon of numerical instability. Consider the sequence x0 = 1.0, x1 = 0.5, xn+1 = 2.5 · xn – xn–1. Algorithms and Data Structures 112 A Global Text | algorithms and data structures_Page_112_Chunk4652 |
13. Reals We first solve this linear recurrence relation in closed form by trying xi=ri for r≠0. This leads to rn+1 = 2.5 · rn– rn–1, and to the quadratic equation 0 = r2– 2.5 · r + 1, with the two solutions r = 2 and r = 0.5. The general solution of the recurrence relation is a linear combination: xi = a · 2i + b · 2–i. The starting values x0 = 1.0 and x1 = 0.5 determine the coefficients a=0 and b=1, and thus the sequence is given exactly as xi = 2–i. If the sequence xi = 2–i is computed by the recurrence relation above in a floating-point number system with one decimal digit, the following may happen: x2 = 2.5 · 0.5 – 1 =0.2 (rounding the exact value 0.25), x3 = 2.5 · 0.2 – 0.5 =0 (represented exactly with one decimal digit), x4 = 2.5 · 0 – 0.2 =–0.2 (represented exactly with one decimal digit), x5 = 2.5 · (–0.2)–0 =–0.5 represented exactly with one decimal digit), x6 = 2.5 · (–0.5)–(–0.2) = –1.05 (exact) = –1.0 (rounded), x7 = 2.5 · (–1) – (–0.5) = –2.0 (represented exactly with one decimal digit), x8 = 2.5 · (–2)–(–1) = –4.0(represented exactly with one decimal digit). As soon as the first rounding error has occurred, the computed sequence changes to the alternative solution x i = a · 2i, as can be seen from the doubling of consecutive computed values. Exercise: floating-point number systems and calculations (a) Consider a floating-point number system with two ternary digits t1, t2 in the mantissa, and a ternary digit e in the exponent to the base 3. Every number in this system has the form x = .t 1 t2 · 3e, where t1, t2, and e assume a value chosen among{0,1,2}. Draw a diagram that shows all the different numbers in this system, and for each number, all of its representations. How many representations are there? How many different numbers? (b) Recall the series which holds for |x| < 1, for example, Use this formula to express 1/0.7 as a series of powers. Horner's method A polynomial of n-th degree (e.g. n = 3) is usually represented in the form a3 · x3 + a2 · x2 + a1 · x + a0 but is better evaluated in nested form, ((a3 · x + a2) · x + a1) · x + a0. 113 | algorithms and data structures_Page_113_Chunk4653 |
This book is licensed under a Creative Commons Attribution 3.0 License The first formula needs n multiplications of the form ai · xi and, in addition, n–1 multiplications to compute the powers of x. The second formula needs only n multiplications in total: The powers of x are obtained for free as a side effect of the coefficient multiplications. The following procedure assumes that the (n+1) coefficients ai are stored in a sufficiently large array a of type 'coeff': type coeff = array[0 .. m] of real; function horner(var a: coeff; n: integer; x: real): real; var i: integer; h: real; begin h := a[n]; for i := n – 1 downto 0 do h := h · x + a[i]; return(h) end; Bisection Bisection is an iterative method for solving equations of the form f(x) = 0. Assuming that the function f : R → R is continuous in the interval [a, b] and that f(a) · f(b) < 0, a root of the equation f(x) = 0 (a zero of f) must lie in the interval [a, b] (Exhibit 13.1). Let m be the midpoint of this interval. If f(m) = 0, m is a root. If f(m) · f(a) < 0, a root must be contained in [a, m], and we proceed with this subinterval; if f(m) · f(b) < 0, we proceed with [m, b]. Thus at each iteration the interval of uncertainty that must contain a root is half the size of the interval produced in the previous iteration. We iterate until the interval is smaller than the tolerance within which the root must be determined. Exhibit 13.1: As in binary search, bisection excludes half of the interval under consideration at every step. function bisect(function f: real; a, b: real): real; const epsilon = 10–6; var m: real; faneg: boolean; begin faneg := f(a) < 0.0; repeat m := (a + b) / 2.0; if (f(m) < 0.0) = faneg then a := m else b := m until |a – b| < epsilon; return(m) Algorithms and Data Structures 114 A Global Text | algorithms and data structures_Page_114_Chunk4654 |
13. Reals end; A sequence x1, x2, x3,… converging to x converges linearly if there exist a constant c and an index i0 such that for all I > i0: |xi+1 – x| ≤ c · |xi – x|. An algorithm is said to converge linearly if the sequence of approximations constructed by this algorithm converges linearly. In a linearly convergent algorithm each iteration adds a constant number of significant bits. For example, each iteration of bisection halves the interval of uncertainty in each iteration (i.e. adds one bit of precision to the result). Thus bisection converges linearly with c = 0.5. A sequence x 1, x2, x3,… converges quadratically if there exist a constant c and an index i0 such that for all i > i0: |xi+1 – x| ≤ c ·|xi – x|2. Newton's method for computing the square root Newton's method for solving equations of the form f(x) = 0 is an example of an algorithm with quadratic convergence. Let f: R → R be a continuous and differentiable function. An approximation xi+1 is obtained from xi by approximating f(x) in the neighborhood of xi by its tangent at the point (xi, f(xi)), and computing the intersection of this tangent with the x-axis (Exhibit 13.2). Hence x i x i+1 f(x )i x Exhibit 13.2: Newton's iteration approximates a curve locally by a tangent. Newton's method is not guaranteed to converge (Exercise: construct counterexamples), but when it converges, it does so quadratically and therefore very fast, since each iteration doubles the number of significant bits. To compute the square root x = √a of a real number a > 0 we consider the function f(x) = x2 – a and solve the equation x2– a = 0. With f'(x)= 2 · x we obtain the iteration formula: The formula that relates xi and xi+1 can be transformed into an analogous formula that determines the propagation of the relative error: 115 | algorithms and data structures_Page_115_Chunk4655 |
This book is licensed under a Creative Commons Attribution 3.0 License Since we obtain for the relative error: Using we get a recurrence relation for the relative error: If we start with x0 > 0, it follows that 1+R0 > 0. Hence we obtain R1 > R2 > R3 > … > 0. As soon as Ri becomes small (i.e. Ri « 1), we have 1 + Ri ≈ 1, and we obtain Ri+1 ≈ o.5 · Ri 2 Newton's method converges quadratically as soon as xi is close enough to the true solution. With a bad initial guess Ri » 1 we have, on the other hand, 1 + Ri ≈ Ri, and we obtain Ri+1 ≈ 0.5 · Ri (i.e. the computation appears to converge linearly until Ri « 1 and proper quadratic convergence starts). Thus it is highly desirable to start with a good initial approximation x0 and get quadratic convergence right from the beginning. We assume normalized binary floating-point numbers (i.e. a = m · 2e with 0.5 ≤ m <1). A good approximation of is obtained by choosing any mantissa c with 0.5 ≤ c < 1 and halving the exponent: In order to construct this initial approximation x0, the programmer needs read and write access not only to a "real number" but also to its components, the mantissa and exponent, for example, by procedures such as procedure mantissa(z: real): integer; procedure exponent(z: real): integer; procedure buildreal(mant, exp: integer): real; Today's programming languages often lack such facilities, and the programmer is forced to use backdoor tricks to construct a good initial approximation. If x0 can be constructed by halving the exponent, we obtain the following upper bounds for the relative error: R1 < 2–2, R2 < 2–5, R3 < 2–11, R4 < 2–23, R5 < 2–47,R6 < 2–95. Algorithms and Data Structures 116 A Global Text | algorithms and data structures_Page_116_Chunk4656 |
13. Reals It is remarkable that four iterations suffice to compute an exact square root for 32-bit floating-point numbers, where 23 bits are used for the mantissa, one bit for the sign and eight bits for the exponent, and that six iterations will do for a "number cruncher" with a word length of 64 bits. The starting value x 0 can be further optimized by choosing c carefully. It can be shown that the optimal value of c for computing the square root of a real number is c = 1/√2 ≈ 0.707. Exercise: square root Consider a floating-point number system with two decimal digits in the mantissa: Every number has the form x = ± .d1 d2 · 10±e. (a) How many different number representations are there in this system? (b) How many different numbers are there in this system? Show your reasoning. (c) Compute √50 · 102 in this number system using Newton's method with a starting value x0 = 10. Show every step of the calculation. Round the result of any operation to two digits immediately. Solution (a) A number representation contains two sign bits and three decimal digits, hence there are 22 · 103 = 4000 distinct number representations in this system. (b) There are three sources of redundancy: 1. Multiple representations of zero 2. Exponent +0 equals exponent –0 3. Shifted mantissa: ±.d0 · 10 ±e=±.0d · 10 ±e + 1 A detailed count reveals that there are 3439 different numbers. Zero has 22·10 = 40 representations, all of the form ±.00·10±e, with two sign bits and one decimal digit e to be freely chosen. Therefore, r1 = 39 must be subtracted from 4000. If e = 0, then ±.d1d2 · 10+0=±.d1d2 · 10–0. We assume furthermore that d1d2 ≠ 00. The case d1d2 = 00 has been covered above. Then there are 2 · 99 such pairs. Therefore, r2= 198 must be subtracted from 4000. If d2 = 0, then ±.d10 · 10±e = ±.0d1 · 10±e+1. The case d1 = 0 has been treated above. Therefore, we assume that d1 ≠ 0. Since ±e can assume the 18 different values –9, –8, … , –1, +0, +1, … +8, there are 2 · 9 · 18 such pairs. Therefore, r3 = 324 must be subtracted from 4000. There are 4000 – r1– r2– r3 = 3439 different numbers in this system. (c) Computing Newton's square root algorithm: x0 = 10 x1 = .50 · (10 + 50/10) = .50 · (10 + 5) = .50 · 15 = 7.5 x2 = .50 · (7.5 + 50/7.5) = .50 · (7.5 + 6.6) = .50 · 14 = 7 x3 = .50 · = .50 · (7 + 50/7) = (7 + 7.1) = .50 · 14 = 7 117 | algorithms and data structures_Page_117_Chunk4657 |
This book is licensed under a Creative Commons Attribution 3.0 License Exercises 1. Write up all the distinct numbers in the floating-point system with number representations of the form z=0.b1b2 · 2e1e2, where b1, b2 and e1, e2 may take the values 0 and 1, and mantissa and exponent are represented in 2's complement notation. 2. Provide simple numerical examples to illustrate floating-point arithmetic violations of mathematical identities. Algorithms and Data Structures 118 A Global Text | algorithms and data structures_Page_118_Chunk4658 |
This book is licensed under a Creative Commons Attribution 3.0 License 14. Straight lines and circles Learning objectives: • intersection of two line segments • degenerate configurations • clipping • digitized lines and circles • Bresenham's algorithms • braiding straight lines Points are the simplest geometric objects; straight lines and line segments come next. Together, they make up the lion's share of all primitive objects used in two-dimensional geometric computation (e.g. in computer graphics). Using these two primitives only, we can approximate any curve and draw any picture that can be mapped onto a discrete raster. If we do so, most queries about complex figures get reduced to basic queries about points and line segments, such as: is a given point to the left, to the right, or on a given line? Do two given line segments intersect? As simple as these questions appear to be, they must be handled efficiently and carefully. Efficiently because these basic primitives of geometric computations are likely to be executed millions of times in a single program run. Carefully because the ubiquitous phenomenon of degenerate configurations easily traps the unwary programmer into overflow or meaningless results. Intersection The problem of deciding whether two line segments intersect is unexpectedly tricky, as it requires a consideration of three distinct nondegenerate cases, as well as half a dozen degenerate ones. Starting with degenerate objects, we have cases where one or both of the line segments degenerate into points. The code below assumes that line segments of length zero have been eliminated. We must also consider nondegenerate objects in degenerate configurations, as illustrated in Exhibit 14.1. Line segments A and B intersect (strictly). C and D, and E and F, do not intersect; the intersection point of the infinitely extended lines lies on C in the first case, but lies neither on E nor on F in the second case. The next three cases are degenerate: G and H intersect barely (i.e. in an endpoint); I and J overlap (i.e. they intersect in infinitely many points); K and L do not intersect. Careless evaluation of these last two cases is likely to generate overflow. Exhibit 14.1: Cases to be distinguished for the segment intersection problem. Computing the intersection point of the infinitely extended lines is a naive approach to this decision problem that leads to a three-step process: Algorithms and Data Structures 119 A Global Text | algorithms and data structures_Page_119_Chunk4659 |
14. Straight lines and circles 1. Check whether the two line segments are parallel (a necessary precaution before attempting to compute the intersection point). If so, we have a degenerate configuration that leads to one of three special cases: not collinear, collinear nonoverlapping, collinear overlapping 2. Compute the intersection point of the extended lines (this step is still subject to numerical problems for lines that are almost parallel). 3. Check whether this intersection point lies on both line segments. If all we want is a yes/no answer to the intersection question, we can save the effort of computing the intersection point and obtain a simpler and more robust procedure based on the following idea: two line segments intersect strictly iff the two endpoints of each line segment lie on opposite sides of the infinitely extended line of the other segment. Let L be a line given by the equation h(x, y) = a · x + b · y + c = 0, where the coefficients have been normalized such that a2 + b2 = 1. For a line L given in this Hessean normal form, and for any point p = (x, y), the function h evaluated at p yields the signed distance between p and L: h(p) > 0 if p lies on one side of L, h(p) < 0 if p lies on the other side, and h(p) = 0 if p lies on L. A line segment is usually given by its endpoints (x 1, y1) and (x2, y2), and the Hessean normal form of the infinitely extended line L that passes through (x1, y1) and (x2, y2) is where is the length of the line segment, and h(x, y) is the distance of p = (x, y) from L. Two points p and q lie on opposite sides of L iff h(p) · h(q) < 0 (Exhibit 14.2). h(p) = 0 or h(q) = 0 signals a degenerate configuration. Among these, h(p) = 0 and h(q) = 0 iff the segment (p, q) is collinear with L. Exhibit 14.2: Segment s, its extended line L, and distance to points p, q as computed by function h. type point = record x, y: real end; segment = record p1, p2: point end; function d(s: segment; p: point): real; { computes h(p) for the line L determined by s } var dx, dy, L12: real; 120 | algorithms and data structures_Page_120_Chunk4660 |
This book is licensed under a Creative Commons Attribution 3.0 License begin dx := s.p2.x – s.p1.x; dy := s.p2.y – s.p1.y; L12 := sqrt(dx · dx + dy · dy); return((dy · (p.x – s.p1.x) – dx · (p.y – s.p1.y)) / L12) end; To optimize the intersection function, we recall the assumption L12 > 0 and notice that we do not need the actual distance, only its sign. Thus the function d used below avoids computing L12. The function 'intersect' begins by checking whether the two line segments are collinear, and if so, tests them for overlap by intersecting the intervals obtained by projecting the line segments onto the x-axis (or onto the y-axis, if the segments are vertical). Two intervals [a, b] and [c, d] intersect iff min(a, b) ≤ max(c, d) and min(c, d) ≤ max(a, b). This condition could be simplified under the assumption that the representation of segments and intervals is ordered "from left to right" (i.e. for interval [a, b] we have a ≤ b). We do not assume this, as line segments often have a natural direction and cannot be "turned around". function d(s: segment; p: point): real; begin return((s.p2.y – s.p1.y) · (p.x – s.p1.x) – (s.p2.x – s.p1.x) · (p.y – s.p1.y)) end; function overlap(a, b, c, d: real): boolean; begin return((min(a, b) ≤ max(c, d)) and (min(c, d) ≤ max(a, b))) end; function intersect(s1, s2: segment): boolean; var d11, d12, d21, d22: real; begin d11 := d(s1, s2.p1); d12 := d(s1, s2.p2); if (d11 = 0) and (d12 = 0) then { s1 and s2 are collinear } if s1.p1.x = s1.p2.x then { vertical } return(overlap(s1.p1.y, s1.p2.y, s2.p1.y, s2.p2.y)) else { not vertical } return(overlap(s1.p1.x, s1.p2.x, s2.p1.x, s2.p2.x)) else begin { s1 and s2 are not collinear } d21 := d(s2, s1.p1); d22 := d(s2, s1.p2); return((d11 · d12 ≤ 0) and (d21 · d22 ≤ 0)) end end; In addition to the degeneracy issues we have addressed, there are numerical issues of near-degeneracy that we only mention. The length L12 is a condition number (i.e. an indicator of the computation's accuracy). As Exhibit 14.3 suggests, it may be numerically impossible to tell on which side of a short line segment L a distant point p lies. Algorithms and Data Structures 121 A Global Text | algorithms and data structures_Page_121_Chunk4661 |
14. Straight lines and circles Exhibit 14.3: A point's distance from a segment amplifies the error of the "which side" computation. Conclusion: A geometric algorithm must check for degenerate configurations explicitly—the code that handles configurations "in general position" will not handle degeneracies. Clipping The widespread use of windows on graphic screens makes clipping one of the most frequently executed operations: Given a rectangular window and a configuration in the plane, draw that part of the configuration which lies within the window. Most configurations consist of line segments, so we show how to clip a line segment given by its endpoints (x1, y1) and (x2, y2) into a window given by its four corners with coordinates {left, right} × {top, bottom}. The position of a point in relation to the window is described by four boolean variables: ll (to the left of the left border), rr (to the right of the right border), bb (below the lower border), tt (above the upper border): type wcode = set of (ll, rr, bb, tt); A point inside the window has the code ll = rr = bb = tt = false, abbreviated 0000 (Exhibit 14.4). Exhibit 14.4: The clipping window partitions the plane into nine regions. The procedure 'classify' determines the position of a point in relation to the window: procedure classify(x, y: real; var c: wcode); begin c := Ø; { empty set } if x < left then c := {ll} elsif x > right then c := {rr}; if y < bottom then c := c ∪ {bb} elsif y > top then c := c ∪ {tt} end; The procedure 'clip' computes the endpoints of the clipped line segment and calls the procedure 'showline' to draw it: procedure clip(x1, y1, x2, y2: real); 122 p L | algorithms and data structures_Page_122_Chunk4662 |
This book is licensed under a Creative Commons Attribution 3.0 License var c, c1, c2: wcode; x, y: real; outside: boolean; begin { clip } classify(x1, y1, c1); classify(x2, y2, c2); outside := false; while (c1 ≠ Ø) or (c2 ≠ Ø) do if c1 ∩ c2 ≠ Ø then { line segment lies completely outside the window } { c1 := Ø; c2 := Ø; outside := true } else begin c := c1; if c = Ø then c := c2; if ll ∈ c then { segment intersects left } { y := y1 + (y2 – y1) · (left – x1) / (x2 – x1); x := left } elsif rr ∈ c then { segment intersects right } { y := y1 + (y2 – y1) · (right – x1) / (x2 – x1); x := right } elsif bb ∈ c then { segment intersects bottom } { x := x1 + (x2 – x1) · (bottom – y1) / (y2 – y1); y := bottom } elsif tt ∈ c then { segment intersects top } { x := x1 + (x2 – x1) · (top – y1) / (y2 – y1); y := top }; if c = c1 then { x1 := x; y1 := y; classify(x, y, c1) } else { x2 := x; y2 := y; classify(x, y, c2) } end; if not outside then showline(x1, y1, x2, y2) end; { clip } Drawing digitized lines A raster graphics screen is an integer grid of pixels, each of which can be turned on or off. Euclidean geometry does not apply directly to such a discretized plane. Any designer using a CAD system will prefer Euclidean geometry to a discrete geometry as a model of the world. The problem of how to approximate the Euclidean plane by an integer grid turns out to be a hard question: How do we map Euclidean geometry onto a digitized space in such a way as to preserve the rich structure of geometry as much as possible? Let's begin with simple instances: How do you map a straight line onto an integer grid, and how do you draw it efficiently? Exhibit 14.5 shows reasonable examples. Exhibit 14.5: Digitized lines look like staircases. Consider the slope m = (y2 – y1) / (x2 – x1) of a segment with endpoints p1 = (x1, y1) and p2 = (x2, y2). If |m| ≤ 1 we want one pixel blackened on each x coordinate; if |m| ≥ 1, one pixel on each y coordinate; these two requirements are consistent for diagonals with |m| = 1. Consider the case |m| ≤ 1. A unit step in x takes us from point (x, y) on the line to (x + 1, y + m). So for each x between x1 and x2 we paint the pixel (x, y) closest to the mathematical line according to the formula y = round(y1 + m · (x – x1)). For the case |m| > 1, we reverse the roles of x and y, taking a unit step in y and incrementing x by 1/m. The following procedure draws line segments with |m| ≤ 1 using unit steps in x. procedure line(x1, y1, x2, y2: integer); var x, sx: integer; m: real; Algorithms and Data Structures 123 A Global Text | algorithms and data structures_Page_123_Chunk4663 |
14. Straight lines and circles begin PaintPixel(x1, y1); if x1 ≠ x2 then begin x := x1; sx := sgn(x2 – x1); m := (y2 – y1) / (x2 – x1); while x ≠ x2 do { x := x + sx; PaintPixel(x, round(y1 + m · (x – x1))) } end end; This straightforward implementation has a number of disadvantages. First, it uses floating-point arithmetic to compute integer coordinates of pixels, a costly process. In addition, rounding errors may prevent the line from being reversible: reversibility means that we paint the same pixels, in reverse order, if we call the procedure with the two endpoints interchanged. Reversibility is desirable to avoid the following blemishes: that a line painted twice, from both ends, looks thicker than other lines; worse yet, that painting a line from one end and erasing it from the other leaves spots on the screen. A weaker constraint, which is only concerned with the result and not the process of painting, is easy to achieve but is less useful. Weak reversibility is most easily achieved by ordering the points p1 and p2 lexicographically by x and y coordinates, drawing every line from left to right, and vertical lines from bottom to top. This solution is inadequate for animation, where the direction of drawing is important, and the sequence in which the pixels are painted is determined by the application—drawing the trajectory of a falling apple from the bottom up will not do. Thus interactive graphics needs the stronger constraint. Efficient algorithms, such as Bresenham's [Bre 65], avoid floating-point arithmetic and expensive multiplications through incremental computation: Starting with the current point p1, a next point is computed as a function of the current point and of the line segment parameters. It turns out that only a few additions, shifts, and comparisons are required. In the following we assume that the slope m of the line satisfies |m| ≤ 1. Let ∆x = x2 – x1, sx = sign(∆x), ∆y = y2 – y1, sy = sign(∆y). Assume that the pixel (x, y) is the last that has been determined to be the closest to the actual line, and we now want to decide whether the next pixel to be set is (x + sx, y) or (x + sx, y + sy). Exhibit 14.6 depicts the case sx = 1 and sy = 1. Exhibit 14.6: At the next coordinate x + sx, we identify and paint the pixel closest to the line. Let t denote the absolute value of the difference between y and the point with abscissa x + sx on the actual line. Then t is given by 124 | algorithms and data structures_Page_124_Chunk4664 |
This book is licensed under a Creative Commons Attribution 3.0 License The value of t determines the pixel to be drawn: As the following example shows, reversibility is not an automatic consequence of the geometric fact that two points determine a unique line, regardless of correct rounding or the order in which the two endpoints are presented. A problem arises when two grid points are equally close to the straight line (Exhibit 14.7). Exhibit 14.7: Breaking the tie among equidistant grid points. If the tie is not broken in a consistent manner (e.g. by always taking the upper grid point), the resulting algorithm fails to be reversible: All the variables introduced in this problem range over the integers, but the ratio (Δ y) (Δ x) appears to introduce rational expressions. This is easily remedied by multiplying everything with ∆x. We define the decision variable d as d = |∆x| · (2 · t – 1) = sx · ∆x · (2 · t – 1). (∗) Let di denote the decision variable which determines the pixel (x (i), y(i)) to be drawn in the i-th step. Substituting t and inserting x = x(i–1) and y = y(i–1) in (∗) we obtain di = sx · sy · (2·∆x · y1 + 2 · (x(i–1) + sx – x1) · ∆y – 2·∆x · y(i–1) – ∆x · sy) and di+1 = sx · sy · (2·∆x · y1 + 2 · (x(i) + sx – x1) · ∆y – 2·∆x · y(i) – ∆x · sy). Subtracting di from di+1, we get di+1 – di = sx · sy · (2 · (x(i) – x(i–1)) · ∆y – 2 · ∆x · (y(i) – y(i–1))). Since x(i) – x(i–1) = sx, we obtain di+1 = di + 2 · sy · ∆y – 2 · sx · ∆x · sy · (y(i) – y(i–1)). Algorithms and Data Structures 125 A Global Text | algorithms and data structures_Page_125_Chunk4665 |
14. Straight lines and circles If di < 0, or di = 0 and sy = –1, then y(i) = y(i–1), and therefore di+1 = di + 2 · |∆y|. If di > 0, or di = 0 and sy = 1, then y(i) = y(i–1) + sy, and therefore di+1 = di + 2 · |∆y| – 2 · |∆x|. This iterative computation of di+1 from the previous di lets us select the pixel to be drawn. The initial starting value for d1 is found by evaluating the formula for di, knowing that (x(0), y(0)) = (x1, y1). Then we obtain d1 = 2 · |∆y| – |∆x|. The arithmetic needed to evaluate these formulas is minimal: addition, subtraction and left shift (multiplication by 2). The following procedure implements this algorithm; it assumes that the slope of the line is between –1 and 1. procedure BresenhamLine(x1, y1, x2, y2: integer); var dx, dy, sx, sy, d, x, y: integer; begin dx := |x2 – x1|; sx := sgn(x2 – x1); dy := |y2 – y1|; sy := sgn(y2 – y1); d := 2 · dy – dx; x := x1; y := y1; PaintPixel(x, y); while x ≠ x2 do begin if (d > 0) or ((d = 0) and (sy = 1)) then { y := y + sy;– 2·dx}; x := x + sx; d := d + 2 · dy; PaintPixel(x, y) end end; The riddle of the braiding straight lines Two straight lines in a plane intersect in at most one point, right? Important geometric algorithms rest on this well-known theorem of Euclidean geometry and would have to be reexamined if it were untrue. Is this theorem true for computer lines, that is, for data objects that represent and approximate straight lines to be processed by a program? Perhaps yes, but mostly no. Yes. It is possible, of course, to program geometric problems in such a way that every pair of straight lines has at most, or exactly, one intersection point. This is most readily achieved through symbolic computation. For example, if the intersection of L1 and L2 is denoted by an expression 'Intersect(L1, L2)' that is never evaluated but simply combined with other expressions to represent a geometric construction, we are free to postulate that 'Intersect(L1, L2)' is a point. No. For reasons of efficiency, most computer applications of geometry require the immediate numerical evaluation of every geometric operation. This calculation is done in a discrete, finite number system in which case the theorem need not be true. This fact is most easily seen if we work with a discrete plane of pixels, and we represent a straight line by the set of all pixels touched by an ideal mathematical line. Exhibit 14.8 shows three digitized straight lines in such a square grid model of plane geometry. Two of the lines intersect in a common interval of three pixels, whereas two others have no pixel in common, even though they obviously intersect. 126 | algorithms and data structures_Page_126_Chunk4666 |
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 14.8: Two intersecting lines may share none, one, or more pixels. With floating-point arithmetic the situation is more complicated; but the fact remains that the Euclidean plane is replaced by a discrete set of points embedded in the plane—all those points whose coordinates are representable in the particular number system being used. Experience with numerical computation, and the hazards of rounding errors, suggests that the question "In how many points can two straight lines intersect?" admits the following answers: • There is no intersection—the mathematically correct intersection cannot be represented in the number system. • A set of points that lie close to each other: for example, an interval. • Overflow aborts the calculation before a result is computed, even if the correct result is representable in the number system being used. Exercise: two lines intersect in how many points? Construct examples to illustrate these phenomena when using floating-point arithmetic. Choose a suitable system G of floating-point numbers and two distinct straight lines ai · x + bi · y + ci = 0 with ai, bi, ci ∈ G, i=1, 2, such that, when all operations are performed in G: (a) There is no point whose coordinates x, y ∈ G satisfy both linear equations. (b) There are many points whose coordinates x, y ∈ G satisfy both linear equations. (c) There is exactly one point whose coordinates x, y ∈ G satisfy both linear equations, but the straightforward computation of x and y leads to overflow. (d) As a consequence of (a) it follows that the definition "two lines intersect they share a common point" is inappropriate for numerical computation. Formulate a numerically meaningful definition of the statement "two line segments intersect". Exercise (b) may suggest that the points shared by two lines are neighbors. Pictorially, if the slopes of the two lines are almost identical, we expect to see a blurred, elongated intersection. We will show that worse things may happen: two straight lines may intersect in arbitrarily many points, and these points are separated by intervals in which the two lines alternate in lying on top of each other. Computer lines may be braided! To understand this Algorithms and Data Structures 127 A Global Text | algorithms and data structures_Page_127_Chunk4667 |
14. Straight lines and circles phenomenon, we need to clarify some concepts: What exactly is a straight line represented on a computer? What is an intersection? There is no one answer, there are many! Consider the analogy of the mathematical concept of real numbers, defined by axioms. When we approximate real numbers on a computer, we have a choice of many different number systems (e.g. various floating-point number systems, rational arithmetic with variable precision, interval arithmetic). These systems are typically not defined by means of axioms, but rather in terms of concrete representations of the numbers and algorithms for executing the operations on these numbers. Similarly, a computer line will be defined in terms of a concrete representation (e.g. two points, a point and a slope, or a linear expression). All we obtain depends on the formulas we use and on the basic arithmetic to operate on these representations. The notion of a straight line can be formalized in many different ways, and although these are likely to be mathematically equivalent, they will lead to data objects with different behavior when evaluated numerically. Performing an operation consists of evaluating a formula. Substituting a formula by a mathematically equivalent one may lead to results that are topologically different, because equivalent formulas may exhibit different sensitivities toward rounding errors. Consider a computer that has only integer arithmetic, i.e. we use only the operations +, –, ·, div. Let Z be the set of integers. Two straight lines gi (i = 1, 2) are given by the following equations: ai · x + bi · y + ci = 0 with ai, bi, ci ∈ Z; bi ≠ 0. We consider the problem of whether two given straight lines intersect in a given point x0. We use the following method: Solve the equations for y [i. e. y = E1(x) and y = E2(x)] and test whether E1(x0) is equal to E2(x0). Is this method suitable? First, we need the following definitions: x ∈ Z is a turn for the pair (E1, E2) iff sign(E1(x) – E2(x)) ≠ sign(E1(x + 1) – E2(x + 1)). An algorithm for the intersection problem is correct iff there are at most two turns. The intuitive idea behind this definition is the recognition that rounding errors may force us to deal with an intersection interval rather than a single intersection point; but we wish to avoid separate intervals. The definition above partitions the x-axis into at most three disjoint intervals such that in the left interval the first line lies above or below the second line, in the middle interval the lines "intersect", and in the right interval we have the complementary relation of the left one (Exhibit 14.9). 128 | algorithms and data structures_Page_128_Chunk4668 |
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 14.9: Desirable consistency condition for intersection of nearly parallel lines. Consider the straight lines: 3 · x – 5 · y + 40 = 0 and 2 · x – 3 · y + 20 = 0 which lead to the evaluation formulas Our naive approach compares the expressions (3 · x + 40) div 5 and (2 · x + 20) div 3. Using the definitions it is easy to calculate that the turns are 7, 8, 10, 11, 12, 14, 15, 22, 23, 25, 26, 27, 29, 30. The straight lines have become step functions that intersect many times. They are braided (Exhibit 14.10). Exhibit 14.10: Braiding straight lines violate the consistency condition of Exhibit 14.9. Exercise: show that the straight lines x – 2 · y = 0 k · x – (2 · k + 1) · y = 0 for any integer k > 0 Algorithms and Data Structures 129 A Global Text g1 > g1 g2 = g1 g2 < g1 g2 g2 y x 2 4 6 8 10 12 14 16 18 20 22 24 26 30 32 34 36 38 9 11 13 15 17 19 21 23 25 27 29 31 y x (3x + 40) div 5 (2x + 20) div 3 | algorithms and data structures_Page_129_Chunk4669 |
14. Straight lines and circles have 2 · k – 1 turns in the first quadrant. Is braiding due merely to integer arithmetic? Certainly not: rounding errors also occur in floating-point arithmetic, and we can construct even more pathological behavior. As an example, consider a floating-point arithmetic with a two-decimal-digit mantissa. We perform the evaluation operation: and truncate intermediate results immediately to two decimal places. Consider the straight lines (Exhibit 14.11) 4.3 · x – 8.3 · y = 0, 1.4 · x – 2.7 · y = 0. Exhibit 14.11: Example to be verified by manual computation. These examples were constructed by intersecting straight lines with almost the same slope—a numerically ill- conditioned problem. While working with integer arithmetic, we made the mistake of using the error-prone 'div' operator. The comparison of rational expressions does not require division. Let a1 · x + b1 · y + c1 = 0 and a2 · x + b2 · y + c2 = 0 be two straight lines. To find out whether they intersect at x0, we have to check whether the equality holds. This is equivalent to b2 · c1 – b1 · c2 = x0 · (a2 · b1 – a1 · b2). The last formula can be evaluated without error if sufficiently large integer arguments are allowed. Another way to evaluate this formula without error is to limit the size of the operands. For example, if a i, bi, ci, and x0 are n-digit binary numbers, it suffices to be able to represent 3n-digit binary numbers and to compute with n-digit and 2n- digit binary numbers. These examples demonstrate that programming even a simple geometric problem can cause unexpected difficulties. Numerical computation forces us to rethink and redefine elementary geometric concepts. 130 0.37 0.39 0.73 0.77 0.81 0.85 0.89 0.93 0.41 0.43 0.45 0.47 y x 1.4 ×ξ 2.7 4.3 ×ξ 8.3 | algorithms and data structures_Page_130_Chunk4670 |
This book is licensed under a Creative Commons Attribution 3.0 License Digitized circles The concepts, problems and techniques we have discussed in this chapter are not at all restricted to dealing with straight lines—they have their counterparts for any kind of digitized spatial object. Straight lines, defined by linear formulas, are the simplest nontrivial spatial objects and thus best suited to illustrate problems and solutions. In this section we show that the incremental drawing technique generalizes in a straightforward manner to more complex objects such as circles. The basic parameters that define a circle are the center coordinates (xc, yc) and the radius r. To simplify the presentation we first consider a circle with radius r centered around the origin. Such a circle is given by the equation x2 + y2 = r2. Efficient algorithms for drawing circles, such as Bresenham's [Bre 77], avoid floating-point arithmetic and expensive multiplications through incremental computation: A new point is computed depending on the current point and on the circle parameters. Bresenham's circle algorithm was conceived for use with pen plotters and therefore generates all points on a circle centered at the origin by incrementing all the way around the circle. We present a modified version of his algorithm which takes advantage of the eight-way symmetry of a circle. If (x, y) is a point on the circle, we can easily determine seven other points lying on the circle (Exhibit 14.12). We consider only the 45˚ segment of the circle shown in the figure by incrementing from x = 0 to x = y = r / , and use eight-way symmetry to display points on the entire circle. Exhibit 14.12: Eightfold symmetry of the circle. Assume that the pixel p = (x, y) is the last that has been determined to be closest to the actual circle, and we now want to decide whether the next pixel to be set is p1 = (x + 1, y) or p2 = (x + 1, y – 1). Since we restrict ourselves to the 45˚ circle segment shown above these pixels are the only candidates. Now define d' = (x + 1)2 + y2 – r2 d" = (x + 1)2 + (y – 1)2 – r2 which are the differences between the squared distances from the center of the circle to p1 (or p2) and to the actual circle. If |d'| ≤ |d"|, then p1 is closer (or equidistant) to the actual circle; if |d'| > |d"|, then p2 is closer. We define the decision variable d as d = d' + d". (∗) We will show that the rule If d ≤ 0 then select p1 else select p2. Algorithms and Data Structures 131 A Global Text | algorithms and data structures_Page_131_Chunk4671 |
14. Straight lines and circles correctly selects the pixel that is closest to the actual circle. Exhibit 14.13 shows a small part of the pixel grid and illustrates the various possible ways [(1) to (5)] how the actual circle may intersect the vertical line at x + 1 in relation to the pixels p1 and p2. Exhibit 14.13: For a given octant of the circle, if pixel p is lit, only two other pixels p1 and p2 need be examined. In cases (1) and (2) p2 lies inside, p1 inside or on the circle, and we therefore obtain d' ≤ 0 and d" < 0. Now d < 0, and applying the rule above will lead to the selection of p 1. Since |d'| ≤ |d"| this selection is correct. In case (3) p 1 lies outside and p2 inside the circle and we therefore obtain d' > 0 and d" < 0. Applying the rule above will lead to the selection of p1 if d ≤ 0, and p2 if d > 0. This selection is correct since in this case d ≤ 0 is equivalent to |d'| ≤ |d"|. In cases (4) and (5) p1 lies outside, p2 outside or on the circle and we therefore obtain d' > 0 and d" ≥ 0. Now d > 0, and applying the rule above will lead to the selection of p2. Since |d'| > |d"| this selection is correct. Let di denote the decision variable that determines the pixel (x(i), y(i)) to be drawn in the i-th step. Starting with (x(0), y(0)) = (0, r) we obtain d1 = 3 – 2 · r. If di ≤ 0, then (x(i), y(i)) = (x(i) + 1, y(i–1)), and therefore di+1 = di + 4 · xi–1 + 6. If di > 0, then (x(i), y(i)) = (x(i) + 1, y(i–1) – 1), and therefore di+1 = di + 4 · (xi–1 – yi–1) + 10. This iterative computation of di+1 from the previous di lets us select the correct pixel to be drawn in the (i + 1)-th step. The arithmetic needed to evaluate these formulas is minimal: addition, subtraction, and left shift (multiplication by 4). The following procedure 'BresenhamCircle' which implements this algorithm draws a circle with center (xc, yc) and radius r. It uses the procedure 'CirclePoints' to display points on the entire circle. In the cases x = y or r = 1 'CirclePoints' draws each of four pixels twice. This causes no problem on a raster display. procedure BresenhamCircle(xc, yc, r: integer); procedure CirclePoints(x, y: integer); begin PaintPixel(xc + x, yc + y); PaintPixel(xc – x, yc + y); PaintPixel(xc + x, yc – y); PaintPixel(xc – x, yc – y); PaintPixel(xc + y, yc + x); PaintPixel(xc – y, yc + x); PaintPixel(xc + y, yc – x); PaintPixel(xc – y, yc – x) end; 132 | algorithms and data structures_Page_132_Chunk4672 |
This book is licensed under a Creative Commons Attribution 3.0 License var x, y, d: integer; begin x := 0; y := r; d := 3 – 2 · r; while x < y do begin CirclePoints(x, y); if d < 0 then d := d + 4 · x + 6 else { d := d + 4 · (x – y) + 10; y := y – 1 }; x := x + 1 end; if x = y then CirclePoints(x, y) end; .i).Bresenham's algorithm:circle; Exercises and programming projects 1. Design and implement an efficient geometric primitive which determines whether two aligned rectangles (i.e. rectangles with sides parallel to the coordinate axes) intersect. 2. Design and implement a geometric primitive function inTriangle(t: triangle; p: point): …; which takes a triangle t given by its three vertices and a point p and returns a ternary value: p is inside t, p is on the boundary of t, p is outside t. 3. Use the functions 'intersect' of in "Intersection" and 'inTriangle' above to program a function SegmentIntersectsTriangle(s: segment; t: triangle): …; to check whether segment s and triangle t share common points. 'SegmentIntersectsTriangle' returns a ternary value: yes, degenerate, no. List all distinct cases of degeneracy that may occur, and show how your code handles them. 4. Implement Bresenham's incremental algorithms for drawing digitized straight lines and circles. 5. Two circles (x', y', r') and (x'', y'', r'') are given by the coordinates of their center and their radius. Find effective formulas for deciding the three-way question whether (a) the circles intersect as lines, (b) the circles intersect as disks, or (c) neither. Avoid the square-root operation whenever possible. Algorithms and Data Structures 133 A Global Text | algorithms and data structures_Page_133_Chunk4673 |
This book is licensed under a Creative Commons Attribution 3.0 License Part IV: Complexity of problems and algorithms Fundamental issues of computation A successful search for better and better algorithms naturally leads to the question "Is there a best algorithm?", whereas an unsuccessful search leads one to ask apprehensively: "Is there any algorithm (of a certain type) to solve this problem?" These questions turned out to be difficult and fertile. Historically, the question about the existence of an algorithm came first, and led to the concepts of computability and decidability in the 1930s. The question about a "best" algorithm led to the development of complexity theory in the 1960s. The study of these fundamental issues of computation requires a mathematical arsenal that includes mathematical logic, discrete mathematics, probability theory, and certain parts of analysis, in particular asymptotics. We introduce a few of these topics, mostly by example, and illustrate the use of mathematical techniques of algorithm analysis on the important problem of sorting. Algorithms and Data Structures 134 A Global Text | algorithms and data structures_Page_134_Chunk4674 |
This book is licensed under a Creative Commons Attribution 3.0 License 15. Computability and complexity Learning objectives: • algorithm • computability • RISC: Reduced Instruction Set Computer • Almost nothing is computable. • The halting problem is undecidable. • complexity of algorithms and problems • Strassen's matrix multiplication Models of computation: the ultimate RISC Algorithm and computability are originally intuitive concepts. They can remain intuitive as long as we only want to show that some specific result can be computed by following a specific algorithm. Almost always an informal explanation suffices to convince someone with the requisite background that a given algorithm computes a specified result. We have illustrated this informal approach throughout Part III. Everything changes if we wish to show that a desired result is not computable. The question arises immediately: "What tools are we allowed to use?" Everything is computable with the help of an oracle that knows the answers to all questions. The attempt to prove negative results about the nonexistence of certain algorithms forces us to agree on a rigorous definition of algorithm. The question "What can be computed by an algorithm, and what cannot?" was studied intensively during the 1930s by Emil Post (1897–1954), Alan Turing (1912–1954), Alonzo Church (1903), and other logicians. They defined various formal models of computation, such as production systems, Turing machines, and recursive functions, to capture the intuitive concept of "computation by the application of precise rules". All these different formal models of computation turned out to be equivalent. This fact greatly strengthens Church's thesis that the intuitive concept of algorithm is formalized correctly by any one of these mathematical systems. We will not define any of these standard models of computation. They all share the trait that they were designed to be conceptually simple: their primitive operations are chosen to be as weak as possible, as long as they retain their property of being universal computing systems in the sense that they can simulate any computation performed on any other machine. It usually comes as a surprise to novices that the set of primitives of a universal computing machine can be so simple as long as these machines possess two essential ingredients: unbounded memory and unbounded time. Most simulations of a powerful computer on a simple one share three characteristics: it is straightforward in principle, it involves laborious coding in practice, and it explodes the space and time requirements of a Algorithms and Data Structures 135 A Global Text | algorithms and data structures_Page_135_Chunk4675 |
15. Computability and complexity computation. The weakness of the primitives, desirable from a theoretical point of view, has the consequence that as simple an operation as integer addition becomes an exercise in programming. The model of computation used most often in algorithm analysis is significantly more powerful than a Turing machine in two respects: (1) its memory is not a tape, but an array, and (2) in one primitive operation it can deal with numbers of arbitrary size. This model of computation is called random access machine, abbreviated as RAM. A RAM is essentially a random access memory, also abbreviated as RAM, of unbounded capacity, as suggested in Exhibit 15.1. The memory consists of an infinite array of memory cells, addressed 0, 1, 2, … . Each cell can hold a number, say an integer, of arbitrary size, as the arrow pointing to the right suggests. Exhibit 15.1: RAM - unbounded address space, unbounded cell size. A RAM has an arithmetic unit and is driven by a program. The meaning of the word random is that any memory cell can be accessed in unit time (as opposed to a tape memory, say, where access time depends on distance). A further crucial assumption in the RAM model is that an arithmetic operation (+, –, ·, /) also takes unit time, regardless of the size of the numbers involved. This assumption is unrealistic in a computation where numbers may grow very large, but often is a useful assumption. As is the case with all models, the responsibility for using them properly lies with the user. To give the reader the flavor of a model of computation, we define a RAM whose architecture is rather similar to real computers, but is unrealistically simple. The ultimate RISC RISC stands for Reduced Instruction Set Computer, a machine that has only a few types of instructions built into the hardware. What is the minimum number of instructions a computer needs to be universal? In theory, one. Consider a stored-program computer of the "von Neumann type" where data and program are stored in the same memory (John von Neumann, 1903–1957). Let the random access memory (RAM) be "doubly infinite": There is a countable infinity of memory cells addressed 0, 1, … , each of which can hold an integer of arbitrary size, or an instruction. We assume that the constant 1 is hardwired into memory cell 1; from 1 any other integer can be constructed. There is a single type of "three-address instruction" which we call "subtract, test and jump", abbreviated as STJ x, y, z where x, y, and z are addresses. Its semantics is equivalent to STJ x, y, z ⇔ x := x – y; if x ≤ 0 then goto z; x, y, and z refer to cells Cx, Cy, and Cz. The contents of Cx and Cy are treated as data (an integer); the contents of Cz, as an instruction (Exhibit 15.2). 136 | algorithms and data structures_Page_136_Chunk4676 |
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 15.2: Stored program computer: data and instructions share the memory. Since this RISC has just one type of instruction, we waste no space on an op-code field. An instruction contains three addresses, each of which is an unbounded integer. In theory, fortunately, three unbounded integers can be packed into the same space required for a single unbounded integer. In the following exercise, this simple idea leads to a well-known technique introduced into mathematical logic by Kurt Gödel (1906 – 1978). Exercise: Gödel numbering (a) Motel Infinity has a countable infinity of rooms numbered 0, 1, 2, … . Every room is occupied, so the sign claims "No Vacancy". Convince the manager that there is room for one more person. (b) Assume that a memory cell in our RISC stores an integer as a sign bit followed by a sequence d0, d1, d2, … of decimal digits, least significant first. Devise a scheme for storing three addresses in one cell. (c) Show how a sequence of positive integers i1, i2, … , in of arbitrary length n can be encoded in a single natural number j: Given j, the sequence can be uniquely reconstructed. Gödel's solution: Basic program fragments This computer is best understood by considering program fragments for simple tasks. These fragments implement simple operations, such as setting a variable to a given constant, or the assignment operator, that are given as primitives in most programming languages. Programming these fragments naturally leads us to introduce basic concepts of assembly language, in particular symbolic and relative addressing. Set the content of cell 0 to 0: STJ 0, 0, .+1 Whatever the current content of cell 0, subtract it from itself to obtain the integer 0. This instruction resides at some address in memory, which we abbreviate as '.', read as "the current value of the program counter". '.+1' is the next address, so regardless of the outcome of the test, control flows to the next instruction in memory. a := b, where a and b are symbolic addresses. Use a temporary variable t: STJ t, t, .+1 { t := 0 } STJ t, b, .+1 { t := –b } STJ a, a, .+1{ a := 0 } STJ a, t, .+1 { a := –t, so now a = b } Exercise: a program library (a) Write RISC programs for a:= b + c, a := b · c, a := b div c, a := b mod c, a := |b|, a : = min(b, c), a := gcd(b, c). Algorithms and Data Structures 137 A Global Text 0 1 2 13 14 . . . 0 1 STJ 0, 0, 14 program counter Executing instruction 13 sets cell 0 to 0, and increments the program counter. | algorithms and data structures_Page_137_Chunk4677 |
15. Computability and complexity (b) Show how this RISC can compute with rational numbers represented by a pair [a, b] of integers denoting numerator and denominator. (c) (Advanced) Show that this RISC is universal, in the sense that it can simulate any computation done by any other computer. The exercise of building up a RISC program library for elementary functions provides the same experience as the equivalent exercise for Turing machines, but leads to the goal much faster, since the primitive STJ is much more powerful than the primitives of a Turing machine. The purpose of this section is to introduce the idea that conceptually simple models of computation are as powerful, in theory, as much more complex models, such as a high-level programming language. The next two sections demonstrate results of an opposite nature: Universal computers, in the sense we have just introduced, are subject to striking limitations, even if we remove any limit on the memory and time they may use. We prove the existence of noncomputable functions and show that the "halting problem" is undecidable. The theory of computability was developed in the 1930s, and greatly expanded in the 1950s and 1960s. Its basic ideas have become part of the foundation that any computer scientist is expected to know. Computability theory is not directly useful. It is based on the concept "computable in principle" but offers no concept of a "feasible computation". Feasibility, rather than "possible in principle", is the touchstone of computer science. Since the 1960s, a theory of the complexity of computation is being developed, with the goal of partitioning the range of computability into complexity classes according to time and space requirements. This theory is still in full development and breaking new ground, in particular in the area of concurrent computation. We have used some of its concepts throughout Part III and continue to illustrate these ideas with simple examples and surprising results. Almost nothing is computable Consider as a model of computation any programming language, with the fictitious feature that it is implemented on a machine with infinite memory and no operational time limits. Nevertheless we reach the conclusion that "almost nothing is computable". This follows simply from the observation that there are fewer programs than problems to be solved (functions to be computed). Both the number of programs and the number of functions are infinite, but the latter is an infinity of higher cardinality. A programming language L is defined over an alphabet A= {a1, a2, … , ak} of k characters. The set of programs in L is a subset of the set A∗ of all strings over A. A∗ is countable, and so is its subset L, as it is in one-to-one correspondence with the natural numbers under the following mapping: 1. Generate all strings in A∗ in order of increasing length and, in case of equal length, in lexicographic order. 2. Erase all strings that do not represent a program according to the syntax rules of L. 3. Enumerate the remaining strings in the originally given order. Among all programs in L we consider only those which compute a (partial) function from the set N = {1, 2, 3, …} of natural numbers into N. This can be recognized by their heading; for example, function f(x: N): N; As this is a subset of L, there exist only countably many such programs. However, there are uncountably many functions f: N → N, as Georg Cantor (1845–1918) proved by his famous diagonalization argument. It starts by assuming the opposite, that the set {f | f: N → N} is countable, then derives 138 | algorithms and data structures_Page_138_Chunk4678 |
This book is licensed under a Creative Commons Attribution 3.0 License a contradiction. If there were only a countable number of such functions, we could enumerate all of them according to the following scheme: f1(1) f1 f1(2) f1(3) f1(4) f2(1) f2(3) f2(4) f2(2) f2 f3 f3(1) f3(3) f3(4) f3(2) 1 2 3 4 ... . . . f4 f4(1) f4(3) f4(4) f4(2) Construct a function g: N → N, g(i) = fi(i) + 1, which is obtained by adding 1 to the diagonal elements in the scheme above. Hence g is different from each fi, at least for the argument i: g(i) ≠ fi(i). Therefore, our assumption that we have enumerated all functions f: N → N is wrong. Since there exists only a countable infinity of programs, but an uncountable infinity of functions, almost all functions are noncomputable. The halting problem is undecidable If we could predict, for any program P executed on any data set D, whether P terminates or not (i.e. whether it will get into an infinite loop), we would have an interesting and useful technique. If this prediction were based on rules that prescribe exactly how the pair (P, D) is to be tested, we could write a program H for it. A fundamental result of computability theory states that under reasonable assumptions about the model of computation, such a halting program H cannot exist. Consider a programming language L that contains the constructs we will use: mainly recursive procedures and procedure parameters. Consider all procedures P in L that have no parameters, a property that can be recognized from the heading procedure P; This simplifies the problem by avoiding any data dependency of termination. Assume that there exists a program H in L that takes as argument any parameterless procedure P in L and decides whether P halts or loops (i.e. runs indefinitely): Consider the behavior of the following parameterless procedure X: procedure X; begin while H(X) do; end; Consider the reference of X to itself; this trick corresponds to the diagonalization in the previous example. Consider further the loop while H(X) do; which is infinite if H(X) returns true (i.e. exactly when X should halt) and terminates if H(X) returns false (i.e. exactly when X should run forever). This trick corresponds to the change of the diagonal g(i) = fi(i) + 1. We obtain: Algorithms and Data Structures 139 A Global Text | algorithms and data structures_Page_139_Chunk4679 |
15. Computability and complexity By definition of X: By construction of X: The fiendishly crafted program X traps H in a web of contradictions. We blame the weakest link in the chain of reasoning that leads to this contradiction, namely the unsupported assumption of the existence of a halting program H. This proves that the halting problem is undecidable. Computable, yet unknown In the preceding two sections we have illustrated the limitations of computability: clearly stated questions, such as the halting problem, are undecidable. This means that the halting question cannot be answered, in general, by any computation no matter how extensive in time and space. There are, of course, lots of individual halting questions that can be answered, asserting that a particular program running on a particular data set terminates, or fails to do so. To illuminate this key concept of theoretical computer science further, the following examples will highlight a different type of practical limitation of computability. Computable or decidable is a concept that naturally involves one algorithm and a denumerably infinite set of problems, indexed by a parameter, say n. Is there a uniform procedure that will solve any one problem in the infinite set? For example, the "question" (really a denumerable infinity of questions) "Can a given integer n > 2 be expressed as the sum of two primes?" is decidable because there exists the algorithm 's2p' that will answer any single instance of this question: procedure s2p(n: integer): boolean; { for n>2, s2p(n) returns true if n is the sum of two primes, false otherwise } function p(k: integer): integer; { for k>0, p(k) returns the k-th prime: p(1) = 2, p(2) = 3, p(3) = 5, … } end; begin for all i, j such that p(i) < n and p(j )< n do if p(i) + p(j) = n then return(true); return(false); end; { s2p } So the general question "Is any given integer the sum of two primes?" is solved readily by a simple program. A single related question, however, is much harder: "Is every even integer >2 the sum of two primes?" Let's try: 4 = 2 + 2, 6 = 3 + 3, 8 = 5 + 3, 10 = 7 + 3 = 5 + 5, 12 = 7 + 5, 14 = 11 + 3 = 7 + 7, 16 = 13 + 3 = 11 + 5, 18 = 13 + 5 = 11 + 7, 20 = 17 + 3 = 13 + 7, 22 = 19 + 3 = 17 + 5 = 11 + 11, 24 = 19 + 5 = 17 + 7 = 13 + 11, 26 = 23 + 3 = 21 + 5 = 19 + 7 = 13 + 13, 28 = 23 + 5 = 17 + 11, 30 = 23 + 7 = 19 + 11 = 17 + 13, 32 = 29 + 3 = 19 + 13, 34 = 31 + 3 = 29 + 5 = 23 + 11 = 17 + 17, 36 = 33 + 3 = 31 + 5 = 29 + 7 = 23 + 13 = 19 + 17. 140 | algorithms and data structures_Page_140_Chunk4680 |
This book is licensed under a Creative Commons Attribution 3.0 License A bit of experimentation suggests that the number of distinct representations as a sum of two primes increases as the target integer grows. Christian Goldbach (1690–1764) had the good fortune of stating the plausible conjecture "yes" to a problem so hard that it has defied proof or counterexample for three centuries. One might ask: Is the Goldbach conjecture decidable? The straight answer is that the concept of decidability does not apply to a single yes/no question such as Goldbach's conjecture. Asking for an algorithm that tells us whether the conjecture is true or false is meaninglessly trivial. Of course, there is such an algorithm! If the Goldbach conjecture is true, the algorithm that says 'yes' decides. If the conjecture is false, the algorithm that says 'no' will do the job. The problem that we don't know which algorithm is the right one is quite compatible with saying that one of those two is the right algorithm. If we package two trivial algorithms into one, we get the following trivial algorithm for deciding Goldbach's conjecture: function GoldbachOracle(): boolean: begin return(GoldbachIsRight) end; Notice that 'GoldbachOracle' is a function without arguments, and 'GoldbachIsRight' is a boolean constant, either true or false. Occasionally, the stark triviality of the argument above is concealed so cleverly under technical jargon as to sound profound. Watch out to see through the following plot. Let us call an even integer > 2 that is not a sum of two primes a counterexample. None have been found as yet, but we can certainly reason about them, whether they exist or not. Define the function G(k: cardinal): boolean; as follows: Goldbach's conjecture is equivalent to G(0) = true. The (implausible) rival conjecture that there is exactly one counterexample is equivalent to G(0) = false, G(1) = true. Although we do not know the value of G(k) for any single k, the definition of G tells us a lot about this artificial function, namely: if G(i) = true for any i, then G(k) = true for all k > i. With such a strong monotonicity property, how can G look? 1. If Goldbach is right, then G is a constant: G(k) = true for all k. 2. If there are a finite number i of exceptions, then G is a step function: G(k) = false for k < i, G(k) = true for k ≥ i. 3. If there is an infinite number of exceptions, then G is again a constant: G(k) = false for all k. Each of the infinitely many functions listed above is obviously computable. Hence G is computable. The value of G(0) determines truth or falsity of Goldbach's conjecture. Does that help us settle this time-honored mathematical puzzle? Obviously not. All we have done is to rephrase the honest statement with which we started this section, "The answer is yes or no, but I don't know which" by the circuitous "The answer can be obtained by evaluating a computable function, but I don't know which one". Algorithms and Data Structures 141 A Global Text | algorithms and data structures_Page_141_Chunk4681 |
15. Computability and complexity Multiplication of complex numbers Let us turn our attention from noncomputable functions and undecidable problems to very simple functions that are obviously computable, and ask about their complexity: How many primitive operations must be executed in evaluating a specific function? As an example, consider arithmetic operations on real numbers to be primitive, and consider the product z of two complex numbers x and y: x = x1 + i · x2 and y = y1 + i · y2, x · y = z = z1 + i · z2. The complex product is defined in terms of operations on real numbers as follows: z1 = x1 · y1 – x2 · y2, z2 = x1 · y2 + x2 · y1. It appears that one complex multiplication requires four real multiplications and two real additions/subtractions. Surprisingly, it turns out that multiplications can be traded for additions. We first compute three intermediate variables using one multiplication for each, and then obtain z by additions and subtractions: p1 = (x1 + x2) · (y1 + y2), p2 = x1 · y1, p3 = x2 · y2, z1 = p2 – p3, z2 = p1 – p2 – p3. This evaluation of the complex product requires only 3 real multiplications, but 5 real additions / subtractions. This trade of one multiplication for three additions may not look like a good deal in practice, because many computers have arithmetic chips with fast multiplication circuitry. In theory, however, the trade is clearly favorable. The cost of an addition grows linearly in the number of digits, whereas the cost of a multiplication using the standard method grows quadratically. The key idea behind this algorithm is that "linear combinations of k products of sums can generate more than k products of simple terms". Let us exploit this idea in a context where it makes a real difference. Complexity of matrix multiplication The complexity of an algorithm is given by its time and space requirements. Time is usually measured by the number of operations executed, space by the number of variables needed at any one time (for input, intermediate results, and output). For a given algorithm it is often easy to count the number of operations performed in the worst and in the best case; it is usually difficult to determine the average number of operations performed (i.e. averaged over all possible input data). Practical algorithms often have time complexities of the order O(log n), O(n2), O(n · log n), O(n2), and space complexity of the order O(n), where n measures the size of the input data. The complexity of a problem is defined as the minimal complexity of all algorithms that solve this problem. It is almost always difficult to determine the complexity of a problem, since all possible algorithms must be considered, including those yet unknown. This may lead to surprising results that disprove obvious assumptions. The complexity of an algorithm is an upper bound for the complexity of the problem solved by this algorithm. An algorithm is a witness for the assertion: You need at most this many operations to solve this problem. A specific algorithm never provides a lower bound on the complexity of a problem— it cannot extinguish the hope for a more efficient algorithm. Occasionally, algorithm designers engage in races lasting decades that result in (theoretically) faster and faster algorithms for solving a given problem. Volker Strassen started such a race with his 1969 paper 142 | algorithms and data structures_Page_142_Chunk4682 |
This book is licensed under a Creative Commons Attribution 3.0 License "Gaussian Elimination Is Not Optimal" [Str 69], where he showed that matrix multiplication requires fewer operations than had commonly been assumed necessary. The race has not yet ended. The obvious way to multiply two n × n matrices uses three nested loops, each of which is iterated n times, as we saw in a transitive hull algorithm in the chapter, “Matrices and graphs: transitive closure”. The fact that the obvious algorithm for matrix multiplication is of time complexity Θ(n3), however, does not imply that the matrix multiplication problem is of the same complexity. Strassen's matrix multiplication The standard algorithm for multiplying two n × n matrices needs n3 scalar multiplications and n2 · (n – 1) additions; for the case of 2 × 2 matrices, eight multiplications and four additions. Seven scalar multiplications suffice if we accept 18 additions/subtractions. Evaluate seven expressions, each of which is a product of sums: p1 = (a11 + a22) · (b11 + b22), p2 = (a21 + a22) · b11 p3 = a11 · (b12 – b22) p4 = a22 · (–b11 + b21) p5 = (a11 + a12) · b22 p6 = (–a11 + a21) · (b11 + b12)p7 = (a12 – a22) · (b21 + b22). The elements of the product matrix are computed as follows: r11 = p1 + p4 – p5 + p7, r12 = p3 + p5, r21 = p2 + p4, r22 = p1 – p2 + p3 + p6. This algorithm does not rely on the commutativity of scalar multiplication. Hence it can be generalized to n × n matrices using the divide-and-conquer principle. For reasons of simplicity consider n to be a power of 2 (i.e. n = 2 k); for other values of n, imagine padding the matrices with rows and columns of zeros up to the next power of 2. An n × n matrix is partitioned into four n/2 × n/2 matrices: The product of two n × n matrices by Strassen's method requires seven (not eight) multiplications and 18 additions/subtractions of n/2 × n/2 matrices. For large n, the work required for the 18 additions is negligible compared to the work required for even a single multiplication (why?); thus we have saved one multiplication out of eight, asymptotically at no cost. Each n/2 × n/2 matrix is again partitioned recursively into four n/4 × n/4 matrices; after log2 n partitioning steps we arrive at 1 × 1 matrices for which matrix multiplication is the primitive scalar multiplication. Let T(n) denote the number of scalar arithmetic operations used by Strassen's method for multiplying two n × n matrices. For n > 1, T(n) obeys the recursive equation Algorithms and Data Structures 143 A Global Text | algorithms and data structures_Page_143_Chunk4683 |
15. Computability and complexity If we are only interested in the leading term of the solution, the constants 7 and 2 justify omitting the quadratic term, thus obtaining Thus the number of primitive operations required to multiply two n × n matrices using Strassen's method is proportional to n2.81, a statement that we abbreviate as "Strassen's matrix multiplication takes time Θ(n2.81)". Does this asymptotic improvement lead to a more efficient program in practice? Probably not, as the ratio grows too slowly to be of practical importance: For n ≈ 1000, for example, we have 5√1024 = 4 (remember: 210 = 1024). A factor of 4 is not to be disdained, but there are many ways to win or lose a factor of 4. Trading an algorithm with simple code, such as straightforward matrix multiplication, for another that requires more elaborate bookkeeping, such as Strassen's, can easily result in a fourfold increase of the constant factor that measures the time it takes to execute the body of the innermost loop. Exercises 1. Prove that the set of all ordered pairs of integers is countably infinite. 2. A recursive function is defined by a finite set of rules that specify the function in terms of variables, nonnegative integer constants, increment ('+1'), the function itself, or an expression built from these by composition of functions. As an example, consider Ackermann's function defined as A(n) = An(n) for n ≥ 1, where Ak(n) is determined by Ak(1) = 2 for k ≥ 1 A1(n) = A1(n–1) + 2 for n ≥ 2 Ak(n) = Ak–1(Ak(n–1)) for k ≥ 2 (a) Calculate A(1) , A(2) , A(3), A(4). (b) Prove that Ak(2) = 4 for k ≥ 1, A1(n) = 2·n for n ≥ 1, A2(n) = 2n for n ≥ 1, A3(n) = 2A 3 (n–1) for n ≥ 2. (c) Define the inverse of Ackermann's function as α(n) = min{m: A(m) ≥ n}. Show that α(n) ≤ 3 for n ≤ 16, that α(n) ≤ 4 for n at most a "tower" of 65536 2's, and that α(n) → ∞ as n → ∞. 144 | algorithms and data structures_Page_144_Chunk4684 |
This book is licensed under a Creative Commons Attribution 3.0 License 3. Complete Strassen's algorithm by showing how to multiply n × n matrices when n is not an exact power of 2. 4. Assume that you can multiply 3 × 3 matrices using k multiplications. What is the largest k that will lead to an asymptotic improvement over Strassen's algorithm? 5. A permutation matrix P is an n × n matrix that has exactly one '1' in each row and each column; all other entries are '0'. A permutation matrix can be represented by an array var a: array[1 .. n] of integer; as follows: a[i] = j if the i-th row of P contains a '1' in the j-th column. 6. Prove that the product of two permutation matrices is again a permutation matrix. 7. Design an algorithm that multiplies in time Θ(n) two permutation matrices given in the array representation above, and stores the result in this same array representation. Algorithms and Data Structures 145 A Global Text | algorithms and data structures_Page_145_Chunk4685 |
This book is licensed under a Creative Commons Attribution 3.0 License 16. The mathematics of algorithm analysis Learning objectives: • worst-case and average performance of an algorithm • growth rate of a function • asymptotics: O(), Ω(), ∴Θ() • asymptotic behavior of sums • solution techniques for recurrence relations • asymptotic performance of divide-and-conquer algorithms • average number of inversions and average distance in a permutation • trees and their properties Growth rates and orders of magnitude To understand a specific algorithm, it is useful to ask and answer the following questions, usually in this order: What is the problem to be solved? What is the main idea on which this algorithm is based? Why is it correct? How efficient is it? The variety of problems is vast, and so is the variety of "main ideas" that lead one to design an algorithm and establish its correctness. True, there are general algorithmic principles or schemas which are problem-independent, but these rarely suffice: Interesting algorithms typically exploit specific features of a problem, so there is no unified approach to understanding the logic of algorithms. Remarkably, there is a unified approach to the efficiency analysis of algorithms, where efficiency is measured by a program's time and storage requirements. This is remarkable because there is great variety in (1) sets of input data and (2) environments (computers, operating systems, programming languages, coding techniques), and these differences have a great influence on the run time and storage consumed by a program. These two types of differences are overcome as follows. Different sets of input data: worst-case and average performance The most important characteristic of a set of data is its size, measured in terms of any unit convenient to the problem at hand. This is typically the number of primitive objects in the data, such as bits, bytes, integers, or any monotonic function thereof, such as the magnitude of an integer. Examples: For sorting, the number n of elements is natural; for square matrices, the number n of rows and columns is convenient; it is a monotonic function (square root) of the actual size n2 of the data. An algorithm may well behave very differently on different data sets of equal size n—among all possible configurations of given size n some will be favorable, others less so. Both the worst-case data set of size n and the average over all data sets of size n provide well-defined and important measures of efficiency. Example: When sorting data sets about whose order nothing is known, average performance is well characterized by averaging run time over all n! permutations of the n elements. Algorithms and Data Structures 146 A Global Text | algorithms and data structures_Page_146_Chunk4686 |
16. The mathematics of algorithm analysis Different environments: focus on growth rate and ignore constants The work performed by an algorithm is expressed as a function of the problem size, typically measured by size n of the input data. By focusing on the growth rate of this function but ignoring specific constants, we succeed in losing a lot of detail information that changes wildly from one computing environment to another, while retaining some essential information that is remarkably invariant when moving a computation from a micro- to a supercomputer, from machine language to Pascal, from amateur to professional programmer. The definition of general measures for the complexity of problems and for the efficiency of algorithms is a major achievement of computer science. It is based on the notions of asymptotic time and space complexity. Asymptotics renounces exact measurement but states how the work grows as the problem size increases. This information often suffices to distinguish efficient algorithms from inefficient ones. The asymptotic behavior of an algorithm is described by the O(), Ω(), Θ(), and o() notations. To determine the amount of work to be performed by an algorithm we count operations that take constant time (independently of n) and data objects that require constant storage space. The time required by an addition, comparison, or exchange of two numbers is typically independent of how many numbers we are processing; so is the storage requirement for a number. Assume that the time required by four algorithms A1, A2, A3, and A4 is log2n, n, n · log2n, and n2, respectively. The following table shows that for sizes of data sets that frequently occur in practice, from n ≈ 10 3 to 106, the difference in growth rate translates into large numerical differences: n A1 = log2n A2 = n A3 = n · log2n A4 = n2 25 = 32 5 25 = 32 5 · 25 = 160 210 ≈ 103 210 = 1024 10 210 ≈ 103 10 · 210 ≈ 104 220 ≈ 106 220 ≈ 106 20 220 ≈ 106 20 · 220 ≈ 2 · 107 240 ≈ 1012 For a specific algorithm these functions are to be multiplied by a constant factor proportional to the time it takes to execute the body of the innermost loop. When comparing different algorithms that solve the same problem, it may well happen that one innermost loop is 10 times faster or slower than another. It is rare that this difference approaches a factor of 100. Thus for n ≈ 1000 an algorithm with time complexity Θ(n · log n) will almost always be much more efficient than an algorithm with time complexity Θ(n2). For small n, say n = 32, an algorithm of time complexity Θ(n2) may be more efficient than one of complexity Θ(n · log n) (e.g. if its constant is 10 times smaller). When we wish to predict exactly how many seconds and bytes a program needs, asymptotic analysis is still useful but is only a small part of the work. We now have to go back over the formulas and keep track of all the constant factors discarded in cavalier fashion by the O() notation. We have to assign numbers to the time consumed by scores of primitive O(1) operations. It may be sufficient to estimate the time consuming primitives, such as floating-point operations; or it may be necessary to include those that are hidden by a high-level programming language and answer questions such as: How long does an array access a[i, j] take? A procedure call? Incrementing the index i in a loop "for i := 0 to n"? Asymptotics Asymptotics is a technique used to estimate and compare the growth behavior of functions. Consider the function 147 | algorithms and data structures_Page_147_Chunk4687 |
This book is licensed under a Creative Commons Attribution 3.0 License f(x) is said to behave like x for x → ∞ and like 1 / x for x → 0. The motivation for such a statement is that both x and 1 / x are intuitively simpler, more easily understood functions than f(x). A complicated function is unlike any simpler one across its entire domain, but it usually behaves like a simpler one as x approaches some particular value. Thus all asymptotic statements include the qualifier x → x0. For the purpose of algorithm analysis we are interested in the behavior of functions for large values of their argument, and all our definitions below assume x → ∞. The asymptotic behavior of functions is described by the O(), Ω(), Θ (), and o() notations, as in f(x) ∈ O(g(x)). Each of these notations assigns to a given function g the set of all functions that are related to g in a well-defined way. Intuitively, O(), Ω(), Θ(), and o() are used to compare the growth of functions, as ≤, ≥, =, and < are used to compare numbers. O(g) is the set of all functions that are ≤ g in a precise technical sense that corresponds to the intuitive notion "grows no faster than g". The definition involves some technicalities signaled by the preamble ∃ ∃c > 0,∃ > ∃x0 ∈ X, ∀ x ≥ x0. It says that we ignore constant factors and initial behavior and are interested only in a function's behavior from some point on. N0 is the set of nonnegative integers, R0 the set of nonnegative reals. In the following definitions X stands for either N0 or R0. Let g: X → X. Definition of O(), "big oh": O(g) := {f: X → X | ∃ c > 0, ∃ x0 ∈ X, ∀ x ≥ xo : f(x) ≤ c · g(x)} We say that f ∈ O(g), or that f grows at most as fast as g(x) for x → ∞. Definition of Ω(), "omega": Ω(g) := {f: X → X ∃ c > 0 x0 ∈ X, ∀ x ≥ x0: f(x) ≥ c · g(x)}. We say that f ∈ O(g), or that f grows at least as fast as g(x) for x → ∞. Definition of Θ(), "theta": Θ(g) := O(g) ∩ Ω(g). We say that f ∈ Θ(g), or that f has the same growth rate as g(x) for x → ∞. Definition of o(), "small oh": We say that f ∈ o(g), or that f grows slower than g(x) for x → ∞. Notation: Most of the literature uses = in place of our ∈, such as in x = O(x2). If you do so, just remember that this = has none of the standard properties of an equality relation—it is neither commutative nor transitive. Thus O(x2) = x is not used, and from x = O(x2) and x2 = O(x2) it does not follow that x = x2. The key to avoiding confusion is the insight that O() is not a function but a set of functions. Summation formulas log2 denotes the logarithm to the base 2, ln the natural logarithm to the base e. Algorithms and Data Structures 148 A Global Text | algorithms and data structures_Page_148_Chunk4688 |
16. The mathematics of algorithm analysis The asymptotic behavior of a sum can be derived by comparing the sum to an integral that can be evaluated in closed form. Let f(x) be a monotonically increasing, integrable function. Then is bounded below and above by sums (Exhibit 16.1): Exhibit 16.1: Bounding a definite integral by lower and upper sums. Letting xi = i + 1, this inequality becomes so 149 f(x) x y x 0 x1 x 2 x n−1 ξ ν | algorithms and data structures_Page_149_Chunk4689 |
This book is licensed under a Creative Commons Attribution 3.0 License Example By substituting with k > 0 in (∗) we obtain and therefore Example By substituting f x=ln x and ∫ln x dx=x⋅ln x−x in (∗∗) we obtain (n+1)⋅ln(n+1)−n−ln(n+1)≤∑ i=1 n ln i≤(n+1)cdotln(n+1)−n , and therefore ∑ i=1 n log2i=(n+1)⋅log2(n+1)−n ln 2 +g(n) withg(n)∈O(log n) Example By substituting in (∗∗) we obtain with g(n) ∈ O(n · log n). Recurrence relations A homogeneous linear recurrence relation with constant coefficients is of the form xn = a1 · xn–1 + a2 · xn–2 + … + ak · xn–k where the coefficients ai are independent of n and x1, x2, … , xn–1 are specified. There is a general technique for solving linear recurrence relations with constant coefficients - that is, for determining x n as a function of n. We will demonstrate this technique for the Fibonacci sequence which is defined by the recurrence Algorithms and Data Structures 150 A Global Text | algorithms and data structures_Page_150_Chunk4690 |
16. The mathematics of algorithm analysis xn = xn–1 + xn–2, x0 = 0, x1 = 1. We seek a solution of the form xn = c · rn with constants c and r to be determined. Substituting this into the Fibonacci recurrence relation yields c · rn = c · rn–1 + c · rn–2 or c · rn–2 · (r2 – r – 1) = 0. This equation is satisfied if either c = 0 or r = 0 or r2 – r – 1 = 0. We obtain the trivial solution xn = 0 for all n if c = 0 or r = 0. More interestingly, r2– r – 1 = 0 for The sum of two solutions of a homogeneous linear recurrence relation is obviously also a solution, and it can be shown that any linear combination of solutions is again a solution. Therefore, the most general solution of the Fibonacci recurrence has the form where c1 and c2 are determined as solutions of the linear equations derived from the initial conditions: which yield the complete solution for the Fibonacci recurrence relation is therefore Recurrence relations that are not linear with constant coefficients have no general solution techniques comparable to the one discussed above. General recurrence relations are solved (or their solutions are approximated or bounded) by trial-and-error techniques. If the trial and error is guided by some general technique, it will yield at least a good estimate of the asymptotic behavior of the solution of most recurrence relations. Example Consider the recurrence relation 151 | algorithms and data structures_Page_151_Chunk4691 |
This book is licensed under a Creative Commons Attribution 3.0 License with a > 0 and b > 0, which appears often in the average-case analysis of algorithms and data structures. When we know from the interpretation of this recurrence that its solution is monotonically nondecreasing, a systematic trial- and-error process leads to the asymptotic behavior of the solution. The simplest possible try is a constant, xn = c. Substituting this into (∗) leads to so xn = c is not a solution. Since the left-hand side xn is smaller than an average of previous values on the right-hand side, the solution of this recurrence relation must grow faster than c. Next, we try a linear function xn = c · n: At this stage of the analysis it suffices to focus on the leading terms of each side: c · n on the left and (c + a) · n on the right. The assumption a > 0 makes the right side larger than the left, and we conclude that a linear function also grows too slowly to be a solution of the recurrence relation. A new attempt with a function that grows yet faster, xn = c · n2, leads to Comparing the leading terms on both sides, we find that the left side is now larger than the right, and conclude that a quadratic function grows too fast. Having bounded the growth rate of the solution from below and above, we try functions whose growth rate lies between that of a linear and a quadratic function, such as xn = c · n1.5. A more sophisticated approach considers a family of functions of the form xn = c · n1+e for any ε > 0: All of them grow too fast. This suggests xn = c · n · log2 n, which gives with g(n) ∈ O(n · log n) and h(n) ∈ O(log n). To match the linear terms on each side, we must choose c such that or c = a · ln 4 ≈ 1.386 · a. Hence we now know that the solution to the recurrence relation (∗) has the form Algorithms and Data Structures 152 A Global Text | algorithms and data structures_Page_152_Chunk4692 |
16. The mathematics of algorithm analysis Asymptotic performance of divide-and-conquer algorithms We illustrate the power of the techniques developed in previous sections by analyzing the asymptotic performance not of a specific algorithm, but rather, of an entire class of divide-and-conquer algorithms. In “Divide and conquer recursion” we presented the following schema for divide-and-conquer algorithms that partition the set of data into two parts: A(D): if simple(D) then return(A0(D)) else 1. divide: partition D into D1 and D2; 2. conquer: R1 := A(D1); R2 := A(D2); 3. combine: return(merge(R1, R2)); Assume further that the data set D can always be partitioned into two halves, D1 and D2, at every level of recursion. Two comments are appropriate: 1. For repeated halving to be possible it is not necessary that the size n of the data set D be a power of 2, n = 2k. It is not important that D be partitioned into two exact halves—approximate halves will do. Imagine padding any data set D whose size is not a power of 2 with dummy elements, up to the next power of 2. Dummies can always be found that do not disturb the real computation: for example, by replicating elements or by appending sentinels. Padding is usually just a conceptual trick that may help in understanding the process, but need not necessarily generate any additional data. 2. Whether or not the divide step is guaranteed to partition D into two approximate halves, on the other hand, depends critically on the problem and on the data structures used. Example: Binary search in an ordered array partitions D into halves by probing the element at the midpoint; the same idea is impractical in a linked list because the midpoint is not directly accessible. Under our assumption of halving, the time complexity T(n) of algorithm A applied to data D of size n satisfies the recurrence relation where f(n) is the sum of the partitioning or splitting time and the "stitching time" required to merge two solutions of size n / 2 into a solution of size n. Repeated substitution yields The term n · T(1) expresses the fact that every data item gets looked at, the second sums up the splitting and stitching time. Three typical cases occur: (a) Constant time splitting and merging f(n) = c yields 153 | algorithms and data structures_Page_153_Chunk4693 |
This book is licensed under a Creative Commons Attribution 3.0 License T(n) = (T(1) + c) · n. Example: Find the maximum of n numbers. (b) Linear time splitting and merging f(n) = a · n + b yields T(n) = a · n · log2 n + (T(1) + b) · n. Examples: Mergesort, quicksort. (c) Expensive splitting and merging: n ∈ o(f(n)) yields T(n) = n · T(1) + O(f(n) · log n) and therefore rarely leads to interesting algorithms. Permutations Inversions Let (ak: 1 ≤ k ≤ n) be a permutation of the integers 1 .. n. A pair (ai, aj), 1 ≤ I < j ≤ n, is called an inversion iff ai > aj. What is the average number of inversions in a permutation? Consider all permutations in pairs; that is, with any permutation A: a1 = x1; a2 = x2; … ; an = xn consider its inverse A', which contains the elements of A in inverse order: a1 = xn; a2 = xn–1; … ; an = x1. In one of these two permutations xi and xj are in the correct order, in the other, they form an inversion. Since there are n· (n – 1) / 2 pairs of elements (xi, xj) with 1 ≤ i < j ≤ n there are, on average, inversions. Average distance Let (ak: 1 ≤ k ≤ n) be a permutation of the natural numbers from 1 to n. The distance of the element ai from its correct position is |ai – i|. The total distance of all elements from their correct positions is Therefore, the average total distance (i.e. the average over all n! permutations) is Algorithms and Data Structures 154 A Global Text | algorithms and data structures_Page_154_Chunk4694 |
16. The mathematics of algorithm analysis Let 1 ≤ i ≤ n and 1 ≤ j ≤ n. Consider all permutations for which ai is equal to j. Since there are (n – 1)! such permutations, we obtain Therefore, the average distance of an element ai from its correct position is therefore Trees Trees are ubiquitous in discrete mathematics and computer science, and this section summarizes some of the basic concepts, terminology, and results. Although trees come in different versions, in the context of algorithms and data structures, "tree" almost always means an ordered rooted tree. An ordered rooted tree is either empty or it consists of a node, called a root, and a sequence of k ordered subtrees T1, T2, … , Tk (Exhibit 16.2). The nodes of an ordered tree that have only empty subtrees are called leaves or external nodes, the other nodes are called internal nodes (Exhibit 16.3). The roots of the subtrees attached to a node are its children; and this node is their parent. 155 | algorithms and data structures_Page_155_Chunk4695 |
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 16.2: Recursive definition of a rooted, ordered tree. The level of a node is defined recursively. The root of a tree is at level 0. The children of a node at level t are at level t + 1. The level of a node is the length of the path from the root of the tree to this node. The height of a tree is defined as the maximum level of all leaves. The path length of a tree is the sum of the levels of all its nodes (Exhibit 16.3). Exhibit 16.3: A tree of height = 4 and path length = 35. A binary tree is an ordered tree whose nodes have at most two children. A 0-2 binary tree is a tree in which every node has zero or two children but not one. A 0-2 tree with n leaves has exactly n – 1 internal nodes. A binary tree of height h is called complete (completely balanced) if it has 2h+1 – 1 nodes (Exhibit 16.4. A binary tree of height h is called almost complete if all its leaves are on levels h – 1 and h, and all leaves on level h are as far left as possible (Exhibit 16.4). Algorithms and Data Structures 156 A Global Text | algorithms and data structures_Page_156_Chunk4696 |
16. The mathematics of algorithm analysis Exhibit 16.4: Examples of well-balanced binary trees. Exercises 1. Suppose that we are comparing implementations of two algorithms on the same machine. For inputs of size n, the first algorithm runs in 9 · n2 steps, while the second algorithm runs in 81 · n · log2 n steps. Assuming that the steps in both algorithms take the same time, for which values of n does the first algorithm beat the second algorithm? 2. What is the smallest value of n such that an algorithm whose running time is 256 · n2 runs faster than an algorithm whose running time is 2n on the same machine? 3. For each of the following functions fi(n), determine a function g(n) such that fi(n) ∈ Θ(g(n)). The function g(n) should be as simple as possible. f1(n) = 0.001 · n7 + n2 + 2 · n f2(n) = n · log n + log n + 1234 · n f3(n) = 5 · n · log n + n2 · log n + n2 f4(n) = 5 · n · log n + n3 + n2 · log n 4. Prove formally that 1024 · n 2+ 5 · n ∈ Θ(n2). 5. Give an asymptotically tight bound for the following summation: 6. Find the most general solutions to the following recurrence relations. 7. Solve the recurrence T(√n) = 2·T() + log2 n. Hint: Make a change of variables m = log2 n. 8. Compute the number of inversions and the total distance for the permutation (3 1 2 4). 157 | algorithms and data structures_Page_157_Chunk4697 |
This book is licensed under a Creative Commons Attribution 3.0 License 17. Sorting and its complexity Learning objectives: • What is sorting? • basic ideas and intrinsic complexity • insertion sort • selection sort • merge sort • distribution sort • a lower bound Ω(n· log n) • Quicksort • Sorting in linear time? • sorting networks What is sorting? How difficult is it? The problem Assume that S is a set of n elements x1, x2, … , xn drawn from a domain X, on which a total order ≤ is defined (i.e. a relation that satisfies the following axioms): ≤ is reflexive (i.e ∀ ∀x ∈ X: x ≤ x) ≤ is antisymmetric (i.e ∀ ∀x, y ∈ X: x ≤ y ∧ y ≤ x ⇒ x = y) ≤ is transitive (i.e ∀ ∀x, y, z ∈ X: x ≤ y ∧ y ≤ z ⇒ x ≤ z) ≤ is total (i.e. ∀ ∀x, y ∈ X ⇒ x ≤ y ∨ y ≤ x) Sorting is the process of generating a sequence such that (i1, i2, … , in) is a permutation of the integers from 1 to n and holds. Phrased abstractly, sorting is the problem of finding a specific permutation (or one among a few permutations, when distinct elements may have equal values) out of n! possible permutations of the n given elements. Usually, the set S of elements to be sorted will be given in a data structure; in this case, the elements of S are ordered implicitly by this data structure, but not necessarily according to the desired order ≤. Typical sorting problems assume that S is given in an array or in a sequential file (magnetic tape), and the result is to be generated in the same structure. We characterize elements by their position in the structure (e.g. A[i] in the array A or by the Algorithms and Data Structures 158 A Global Text | algorithms and data structures_Page_158_Chunk4698 |
17. Sorting and its complexity value of a pointer in a sequential file). The access operations provided by the underlying data structure determine what sorting algorithms are possible. Algorithms Most sorting algorithms are refinements of the following idea: while ∃(i, j): i < j ∧ A[i] > A[j] do A[i] :=: A[j]; where :=: denotes the exchange operator. Even sorting algorithms that do not explicitly exchange pairs of elements, or do not use an array as the underlying data structure, can usually be thought of as conforming to the schema above. An insertion sort, for example, takes one element at a time and inserts it in its proper place among those already sorted. To find the correct place of insertion, we can think of a ripple effect whereby the new element successively displaces (exchanges position with) all those larger than itself. As the schema above shows, two types of operations are needed in order to sort: • collecting information about the order of the given elements • ordering the elements (e.g. by exchanging a pair) When designing an efficient algorithm we seek to economize the number of operations of both types: We try to avoid collecting redundant information, and we hope to move an element as few times as possible. The nondeterministic algorithm given above lets us perform any one of a number of exchanges at a given time, regardless of their usefulness. For example, in sorting the sequence x1 = 5, x2 = 2, x3 = 3, x4 = 4, x5 = 1 the nondeterministic algorithm permits any of seven exchanges x1 :=: xi for 2 ≤ i ≤ 5 and xj :=: x5 for 2 ≤ j ≤ 4. We might have reached the state shown above by following an exotic sorting technique that sorts "from the middle toward both ends", and we might know at this time that the single exchange x1 :=: x5 will complete the sort. The nondeterministic algorithm gives us no handle to express and use this knowledge. The attempt to economize work forces us to depart from nondeterminacy and to impose a control structure that carefully sequences the operations to be performed so as to make maximal use of the information gained so far. The resulting algorithms will be more complex and difficult to understand. It is useful to remember, though, that sorting is basically a simple problem with a simple solution and that all the acrobatics in this chapter are due to our quest for efficiency. Intrinsic complexity There are obvious limits to how much we can economize. In the absence of any previously acquired information, it is clear that each element must be inspected and, in general, moved at least once. Thus we cannot hope to get away with fewer than Ω(n) primitive operations. There are less obvious limits, we mention two of them here. 1. If information is collected by asking binary questions only (any question that may receive one of two answers (e.g. a yes/no question, or a comparison of two elements that yields either ≤ or >), then at least n · log2 n questions are necessary in general, as will be proved in the section "A lower bound Ωn · logn". Thus in this model of computation, sorting requires time Θ(n · log n). 2. In addition to collecting information, one must rearrange the elements. In the section "Permutation" in chapter 16, we have shown that in a permutation the average distance of an element from its correct 159 | algorithms and data structures_Page_159_Chunk4699 |
This book is licensed under a Creative Commons Attribution 3.0 License position is approximately n/3. Therefore elements have to move an average distance of approximately n/3 elements to end up at their destination. Depending on the access operations of the underlying storage structure, an element can be moved to its correct position in a single step of average length n/3, or in n/3 steps of average length 1. If elements are rearranged by exchanging adjacent elements only, then on average Θ(n2) moving operations are required. Therefore, short steps are insufficient to obtain an efficient Θ(n · log n) sorting algorithm. Practical aspects of sorting Records instead of elements. We discuss sorting assuming only that the elements to be sorted are drawn from a totally ordered domain. In practice these elements are just the keys of records that contain additional data associated with the key: for example, type recordtype = record key: keytype; { totally ordered by ≤ } data: anytype end; We use the relational operators =, <, ≤ to compare keys, but in a given programming language, say Pascal, these may be undefined on values of type keytype. In general, they must be replaced by procedures: for example, when comparing strings with respect to the lexicographic order. If the key field is only a small part of a large record, the exchange operation :=:, interpreted literally, becomes an unnecessarily costly copy operation. This can be avoided by leaving the record (or just its data field) in place, and only moving a small surrogate record consisting of a key and a pointer to its associated record. Sort generators. On many systems, particularly in the world of commercial data processing, you may never need to write a sorting program, even though sorting is a frequently executed operation. Sorting is taken care of by a sort generator, a program akin to a compiler; it selects a suitable sorting algorithm from its repertoire and tailors it to the problem at hand, depending on parameters such as the number of elements to be sorted, the resources available, the key type, or the length of the records. Partially sorted sequences. The algorithms we discuss ignore any order that may exist in the sequence to be sorted. Many applications call for sorting files that are almost sorted, for example, the case where a sorted master file is updated with an unsorted transaction file. Some algorithms take advantage of any order present in the input data; their time complexity varies from O(n) for almost sorted files to O(n · log n) for randomly ordered files. Types of sorting algorithms Two important classes of incremental sorting algorithms create order by processing each element in turn and placing it in its correct position. These classes, insertion sorts and selection sorts, are best understood as maintaining two disjoint, mutually exhaustive structures called 'sorted' and 'unsorted'. Initialize: 'sorted' := Ø; 'unsorted' := {x1, x2, … , xn}; Loop: for i := 1 to n do move an element from 'unsorted' to its correct place in 'sorted'; The following illustrations show 'sorted' and 'unsorted' sharing an array[1 .. n]. In this case the boundary between 'sorted' and 'unsorted' is represented by an index i that increases as more elements become ordered. The important distinction between the two types of sorting algorithms emerges from the question: In which of the two Algorithms and Data Structures 160 A Global Text | algorithms and data structures_Page_160_Chunk4700 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.