taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

Volume C2 · Information structures · TAOCP Section 2.2.3

Linked allocation

Draft. This chapter is written and checked by the tools of the project, and a person has not reviewed it yet. Read it with care.

Read it next to Section 2.2.3 of the book. Study the section: what to read first and the exercises, easiest first. The items of the section and their status.

Read first
  • C2.2.2, in C2. Information structures not written yet
  • C1.3.1, in C1. Basic concepts not written yet
Contents
  1. Linked lists and topological sorting

Linked lists and topological sorting

Overview

A linked list keeps one word, the link, in each node. The link holds the address of the next node, and the last node holds the null link Λ\Lambda. The nodes can lie anywhere in memory, so an insertion or a deletion in the middle of a list changes one or two links and moves no data. Section 2.2.3 of TAOCP shows how a program gets and frees such nodes, how a stack and a queue work on links, and how a large algorithm, the topological sort, uses linked lists for all its tables. This chapter follows that order. Every operation has a table of states, and the topological sort has a complete program with an exact running time.

The ideas

Links replace order in memory. A sequential list gets its order from the addresses. A linked list gets its order from the links. The jjth node of a sequential list is at L0+cjL_0 + cj, and a linked list has no such rule: to reach the jjth node the program follows j−1j - 1 links from the first node. In exchange, a list can grow while other lists grow, and no list owns a fixed area.

One pool of free nodes serves all lists. The free nodes form a linked list too. A variable AVAIL holds the address of its first node. To get a node, take the first node of this list. To free a node, put it first on this list. Both operations are a stack operation on AVAIL, and they take a fixed small time.

The pool can grow into free memory. A program may not know how many nodes it needs. It can keep a second variable, POOLMAX, that marks the first word of memory that no node has used yet. When AVAIL is empty, the program takes a node at POOLMAX and moves POOLMAX up by the size of a node.

A linked stack is a list with a pointer to the top. The top node is the first node of the list. Push takes a node from AVAIL, fills it, and links it before the old top. Pop does the reverse. Each operation changes three links, and the three links are permuted in a cycle.

A linked queue is a list with two pointers. One pointer is at the front and one is at the rear. The empty queue is the one case that needs care: the rear pointer must name a place where the next insertion can write the link of the first node.

A partial order has an arrangement in a line. Given a set of objects and a list of pairs j≺kj \prec k, a topological sort writes the objects in a row so that jj comes before kk for each pair. The row exists exactly when the pairs have no loop. The algorithm counts, for each object, how many pairs still wait on it, and keeps the objects with count zero in a queue.

Definitions, results and proofs

Definition C2.2.2.3.1 (a linked list of nodes, TAOCP eqs. 2.2.3(1) to (3)). A node is a block of words with two parts, INFO and LINK. A linked list with nn items is a variable FIRST and nn nodes N1,…,NnN_1, \ldots, N_n with FIRST=LOC(N1)\mathrm{FIRST} = \mathrm{LOC}(N_1), LINK(Ni)=LOC(Ni+1)\mathrm{LINK}(N_i) = \mathrm{LOC}(N_{i+1}) for i<ni < n, and LINK(Nn)=Λ\mathrm{LINK}(N_n) = \Lambda. The empty list has FIRST=Λ\mathrm{FIRST} = \Lambda.

Node: 2.2.3-(1) · Lean: not yet stated

Explanation. The address Λ\Lambda is a value that no node has, in a program often 00. The list is the chain of links, and the position of each node in memory has no meaning. To insert a node PP after the node QQ, the program sets LINK(P)←LINK(Q)\mathrm{LINK}(P) \leftarrow \mathrm{LINK}(Q) and then LINK(Q)←P\mathrm{LINK}(Q) \leftarrow P. The order of the two assignments matters: the first reads the old link of QQ.

Example. Let FIRST =120= 120 and let the nodes be 120→40→85→Λ120 \to 40 \to 85 \to \Lambda with items a,b,ca, b, c. The list is a,b,ca, b, c. Insert a new node at 6060 with item xx after the node at 4040. Set LINK(60)←LINK(40)=85\mathrm{LINK}(60) \leftarrow \mathrm{LINK}(40) = 85, then LINK(40)←60\mathrm{LINK}(40) \leftarrow 60. The chain is now 120→40→60→85→Λ120 \to 40 \to 60 \to 85 \to \Lambda and the list is a,b,x,ca, b, x, c. No other node changed.

Definition C2.2.2.3.2 (take a node from AVAIL and return a node, TAOCP eqs. 2.2.3(4) and (5)). Let AVAIL be the address of the first free node, or Λ\Lambda when there is none. To take a node into the variable PP: P←AVAILP \leftarrow \mathrm{AVAIL}, AVAIL←LINK(AVAIL)\mathrm{AVAIL} \leftarrow \mathrm{LINK}(\mathrm{AVAIL}). To return the node PP: LINK(P)←AVAIL\mathrm{LINK}(P) \leftarrow \mathrm{AVAIL}, AVAIL←P\mathrm{AVAIL} \leftarrow P.

Node: 2.2.3-(4) · Lean: not yet stated

Explanation. The two operations are push and pop on a stack whose nodes are the free nodes. The taken node still holds the old link, so the program must overwrite the link before it uses the node as part of a list.

Example. Let AVAIL =200= 200 and the free chain be 200→202→204→Λ200 \to 202 \to 204 \to \Lambda. A take gives P=200P = 200 and AVAIL =202= 202. A return of 200200 gives LINK(200)=202\mathrm{LINK}(200) = 202 and AVAIL =200= 200 again. The chain is the same as at the start.

Definition C2.2.2.3.3 (the test for overflow, TAOCP eq. 2.2.3(6)). The take of a node has the test: if AVAIL=Λ\mathrm{AVAIL} = \Lambda then OVERFLOW, before P←AVAILP \leftarrow \mathrm{AVAIL}. The test makes the take safe, and the program can then stop, or free memory, or ask for more.

Node: 2.2.3-(6) · Lean: not yet stated

Explanation. In a linked method the overflow means that the whole pool is empty, not that one list is full. This is the main gain over the sequential method of Section 2.2.2, where a list can overflow while other lists have room.

Example. With AVAIL =Λ= \Lambda the test sends the program to OVERFLOW. With AVAIL =204= 204 and LINK(204)=Λ\mathrm{LINK}(204) = \Lambda, the take succeeds and leaves AVAIL =Λ= \Lambda. The next take overflows.

Definition C2.2.2.3.4 (the pool that grows into free memory, TAOCP eq. 2.2.3(7)). The program keeps POOLMAX, the address of the first word that no node has used, and SEQMIN, the first word that is not available to nodes. A take is: if AVAIL≠Λ\mathrm{AVAIL} \neq \Lambda then take from AVAIL, else P←POOLMAXP \leftarrow \mathrm{POOLMAX}, POOLMAX←POOLMAX+c\mathrm{POOLMAX} \leftarrow \mathrm{POOLMAX} + c, and if POOLMAX>SEQMIN\mathrm{POOLMAX} > \mathrm{SEQMIN} then OVERFLOW. Nodes have cc words.

Node: 2.2.3-(7) · Lean: not yet stated

Explanation. The first nodes are made on demand and the freed nodes are reused first. The program needs no loop to link all nodes at the start. A node at the address PP fits when P+c≤SEQMINP + c \le \mathrm{SEQMIN}, so the test above is the exact test. After an overflow the program must put POOLMAX back to its old value, or it must stop.

Example. Let L0=300L_0 = 300, c=2c = 2 and SEQMIN=306\mathrm{SEQMIN} = 306. The pool has the room for three nodes, at 300300, 302302 and 304304. The table shows the state after each operation. AVAIL is shown as the chain of free nodes, front first.

Operation PP AVAIL chain POOLMAX
start empty 300
take 300 empty 302
take 302 empty 304
return 300 300 304
take 300 empty 304
take 304 empty 306
take none, OVERFLOW empty 308

The last take computes POOLMAX=308>306\mathrm{POOLMAX} = 308 > 306 and signals overflow. A program that goes on resets POOLMAX to 306306. The fourth take reuses the node at 300300 and does not move POOLMAX.

Definition C2.2.2.3.5 (push and pop on a linked stack, TAOCP eqs. 2.2.3(8) and (9)). Let T be the address of the top node, with T=ΛT = \Lambda for the empty stack. Push of yy: take a node PP from AVAIL (with the test), INFO(P)←y\mathrm{INFO}(P) \leftarrow y, LINK(P)←T\mathrm{LINK}(P) \leftarrow T, T←PT \leftarrow P. Pop into yy: if T=ΛT = \Lambda then UNDERFLOW; P←TP \leftarrow T, T←LINK(P)T \leftarrow \mathrm{LINK}(P), y←INFO(P)y \leftarrow \mathrm{INFO}(P), and return PP to AVAIL.

Node: 2.2.3-(8) · Lean: not yet stated

Explanation. The stack is a list whose first node is the top, so push and pop touch only the first node. Push moves a node from the free stack to the item stack, and pop moves it back. There is no limit on the size of the stack other than the pool.

Example. The four operations of the program below, with items 4141 and 5252 and a pool of three nodes, are run in the next block.

Definition C2.2.2.3.6 (the cycle of three links, a remark on TAOCP eqs. 2.2.3(8) and (9)). Let AA be the value of AVAIL, tt the value of T and xx the value of LINK(A)\mathrm{LINK}(A) before a push. After the push, the triple (AVAIL,T,LINK(P))(\mathrm{AVAIL}, \mathrm{T}, \mathrm{LINK}(P)) has changed from (A,t,x)(A, t, x) to (x,A,t)(x, A, t), with P=AP = A. A pop changes the triple back.

Node: 2.2.3-def-cycle · Lean: not yet stated

Explanation. Push and pop do not make or lose any link value. They only rotate three values among three places. This is why a push followed by a pop gives the state before the push, except for the item stored in the freed node.

Example. Before the first push in the run below the triple is (200,Λ,202)(200, \Lambda, 202), since LINK(200)=202\mathrm{LINK}(200) = 202. After the push it is (202,200,Λ)(202, 200, \Lambda). The value 202202 went to AVAIL, 200200 went to T and Λ\Lambda went to LINK(200)\mathrm{LINK}(200).

Program C2.2.2.3.7 (push and pop in MIX, TAOCP programs 2.2.3(10) and (11)). A node is one word with LINK=(0:2)\mathrm{LINK} = (0{:}2) and INFO=(3:5)\mathrm{INFO} = (3{:}5). The cells AVAIL and T hold a link in their (4:5)(4{:}5) field. The cell Y holds the item in its low three bytes. The register rI1 is PP.

Node: 2.2.3-prog-pushpop · Lean: not yet stated

PUSH  LD1  AVAIL(4:5)   P <- AVAIL
      J1Z  OVERFLOW     if P = 0
      LDA  Y
      STA  0,1(INFO)    INFO(P) <- Y
      LDA  0,1(LINK)
      STA  AVAIL        AVAIL <- LINK(P)
      LDA  T
      STA  0,1(LINK)    LINK(P) <- T
      ST1  T(4:5)       T <- P
POP   LD1  T(4:5)       P <- T
      J1Z  UNDERFLOW    if P = 0
      LDA  0,1(INFO)
      STA  Y            Y <- INFO(P)
      LDA  0,1(LINK)
      STA  T            T <- LINK(P)
      LDA  AVAIL
      STA  0,1(LINK)    LINK(P) <- AVAIL
      ST1  AVAIL(4:5)   AVAIL <- P

Cost. Push takes 2+1+2+2+2+2+2+2+2=17u2 + 1 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 17u, and pop takes 17u17u also. The sequential push and pop of Section 2.2.2 take 6u6u and 4u4u with the pointer in a register, so the linked stack is slower by a factor between 33 and 44. The linked stack pays for the freedom of having no area.

Run. The pool is the chain 200→202→204→Λ200 \to 202 \to 204 \to \Lambda, AVAIL =200= 200, T=ΛT = \Lambda. The operations are push 4141, push 5252, pop, pop, pop. The columns for the nodes show (LINK,INFO)(\mathrm{LINK}, \mathrm{INFO}), with a dash when INFO was never set. The values are from a run of the code above on a MIX model.

Operation AVAIL T node 200 node 202 node 204 yy time
start 200 Λ\Lambda (202,−)(202, -) (204,−)(204, -) (Λ,−)(\Lambda, -)
push 41 202 200 (Λ,41)(\Lambda, 41) (204,−)(204, -) (Λ,−)(\Lambda, -) 17u
push 52 204 202 (Λ,41)(\Lambda, 41) (200,52)(200, 52) (Λ,−)(\Lambda, -) 17u
pop 202 200 (Λ,41)(\Lambda, 41) (204,52)(204, 52) (Λ,−)(\Lambda, -) 52 17u
pop 200 Λ\Lambda (202,41)(202, 41) (204,52)(204, 52) (Λ,−)(\Lambda, -) 41 17u
pop 200 Λ\Lambda (202,41)(202, 41) (204,52)(204, 52) (Λ,−)(\Lambda, -) UNDERFLOW 3u

The items 5252 and 4141 stay in the freed nodes but are not part of any list. The last pop stops after LD1\mathrm{LD1} and J1Z\mathrm{J1Z}, which is 2+1=3u2 + 1 = 3u. The last push left LINK(202)=200\mathrm{LINK}(202) = 200 and the first pop gave it back the value 204204, which is the old AVAIL.

Definition C2.2.2.3.8 (insertion into a linked queue, TAOCP eq. 2.2.3(14)). A linked queue has a head cell whose LINK is the front pointer F, and a variable R, the address of the last node. For the empty queue, F=ΛF = \Lambda and R is the address of the head cell. Insertion of yy: take a node PP, INFO(P)←y\mathrm{INFO}(P) \leftarrow y, LINK(P)←Λ\mathrm{LINK}(P) \leftarrow \Lambda, LINK(R)←P\mathrm{LINK}(R) \leftarrow P, R←PR \leftarrow P.

Node: 2.2.3-(14) · Lean: not yet stated

Explanation. With R at the head cell in the empty case, the assignment LINK(R)←P\mathrm{LINK}(R) \leftarrow P sets F to PP and needs no test. The insertion has no special case. The queue grows at the rear, and only R changes.

Example. See the run after the next definition.

Definition C2.2.2.3.9 (deletion from a linked queue, TAOCP eq. 2.2.3(17)). Deletion into yy: if F=ΛF = \Lambda then UNDERFLOW; P←FP \leftarrow F, F←LINK(P)F \leftarrow \mathrm{LINK}(P), y←INFO(P)y \leftarrow \mathrm{INFO}(P), return PP to AVAIL. If now F=ΛF = \Lambda, set R to the address of the head cell.

Node: 2.2.3-(17) · Lean: not yet stated

Explanation. The last step restores the empty case. Without it, R would name the node that was just freed, and the next insertion would write into a free node. The invariant of the queue is: R is the address of the last node when the queue is not empty, and it is the address of the head cell when the queue is empty.

Example. The head cell is at 5050, and its LINK field is F. The nodes come from the addresses 7070, 7474, 7878. The table shows the state after each operation. The pair (LINK,INFO)(\mathrm{LINK}, \mathrm{INFO}) is shown for each node in use.

Operation F R node 70 node 74 node 78 yy
start Λ\Lambda 50
insert aa at 70 70 70 (Λ,a)(\Lambda, a)
insert bb at 74 70 74 (74,a)(74, a) (Λ,b)(\Lambda, b)
delete 74 74 freed (Λ,b)(\Lambda, b) aa
delete Λ\Lambda 50 freed freed bb
delete Λ\Lambda 50 freed freed UNDERFLOW
insert cc at 78 78 78 freed freed (Λ,c)(\Lambda, c)

After the second delete, F is Λ\Lambda and R is reset to 5050. The insertion of cc then writes 7878 in the LINK field of the cell 5050, which is F. The items come out in the order of insertion.

Definition C2.2.2.3.10 (partial order, TAOCP Section 2.2.3). A relation ⪯\preceq on a set SS is a partial order when it has three properties. It is reflexive: x⪯xx \preceq x for all xx. It is antisymmetric: x⪯yx \preceq y and y⪯xy \preceq x give x=yx = y. It is transitive: x⪯yx \preceq y and y⪯zy \preceq z give x⪯zx \preceq z. The relation x≺yx \prec y means x⪯yx \preceq y and x≠yx \neq y.

Node: 2.2.3-def-partial-order · Lean: not yet stated

Explanation. The relation ≺\prec is transitive, and no xx has x≺xx \prec x. The algorithm below takes a list of pairs j≺kj \prec k, not the whole relation. The list can omit pairs that follow by transitivity. A program uses ≺\prec to say "jj must come before kk".

Example. On S={1,2,3,4,6,12}S = \{1, 2, 3, 4, 6, 12\} let x⪯yx \preceq y mean that xx divides yy. Reflexivity and transitivity are clear, and antisymmetry holds because x∣yx \mid y and y∣xy \mid x give x=yx = y for positive integers. The relation ≺\prec has 1212 pairs: 1≺2,3,4,6,121 \prec 2, 3, 4, 6, 12; 2≺4,6,122 \prec 4, 6, 12; 3≺6,123 \prec 6, 12; 4≺124 \prec 12; 6≺126 \prec 12. Not all elements compare: 22 and 33 are not related, and neither are 44 and 66.

Lemma C2.2.2.3.11 (an element with no predecessor). Let SS be a nonempty finite set with a transitive relation ≺\prec such that x≺xx \prec x holds for no xx. Then some x∈Sx \in S has no yy with y≺xy \prec x.

Proof. Suppose that every element has a predecessor. Pick x0x_0, then choose x1≺x0x_1 \prec x_0, then x2≺x1x_2 \prec x_1, and so on. The set is finite, so two of the chosen elements are equal: xj=xix_j = x_i with j>ij > i. By transitivity xj≺xix_j \prec x_i, since xj≺xj−1≺⋯≺xix_j \prec x_{j-1} \prec \cdots \prec x_i. Hence xi≺xix_i \prec x_i, which the hypothesis excludes. □\square

Theorem C2.2.2.3.12 (embedding in a linear order, TAOCP Section 2.2.3). Let SS be a finite set with a relation ≺\prec that is transitive and has x≺xx \prec x for no xx. Then the elements of SS can be written in a row a1,a2,…,ana_1, a_2, \ldots, a_n such that ai≺aja_i \prec a_j implies i<ji < j.

Node: 2.2.3-thm-embedding · Lean: not yet stated

Proof. Induction on n=∣S∣n = |S|. For n=0n = 0 the empty row works. Let n≥1n \ge 1. By the Lemma, some aa has no predecessor. The set S′=S∖{a}S' = S \setminus \{a\} with the same relation satisfies the hypothesis, and it has n−1n - 1 elements. By induction, S′S' has a row a2,…,ana_2, \ldots, a_n. Put a1=aa_1 = a in front. A pair ai≺aja_i \prec a_j has j≠1j \ne 1, since a1a_1 has no predecessor. If i=1i = 1 then i<ji < j. If i≥2i \ge 2, both are in S′S', and i<ji < j by the choice of the row. □\square

Explanation. The proof is also an algorithm: remove an element with no predecessor, write it, and repeat. The cost lies in finding such an element each time. Algorithm T does this in total time linear in the size of the input.

Example. The divisibility order above has 55 rows: 1 2 3 4 6 121\,2\,3\,4\,6\,12, 1 2 3 6 4 121\,2\,3\,6\,4\,12, 1 2 4 3 6 121\,2\,4\,3\,6\,12, 1 3 2 4 6 121\,3\,2\,4\,6\,12 and 1 3 2 6 4 121\,3\,2\,6\,4\,12. The count of 55 was checked with a program that tries all 720720 orders of the six elements. Every row starts with 11 and ends with 1212.

Definition C2.2.2.3.13 (a list of relations as input, TAOCP eq. 2.2.3(18)). The input of the topological sort is nn, the number of objects, numbered 1,…,n1, \ldots, n, and mm pairs (ji,ki)(j_i, k_i) with 1≤ji,ki≤n1 \le j_i, k_i \le n. A pair (j,k)(j, k) means j≺kj \prec k. A repeated pair counts twice in the count of kk, and it is also counted down twice.

Node: 2.2.3-(18) · Lean: not yet stated

Explanation. The pairs are in any order. The algorithm needs only the pairs, not their transitive closure. A pair (j,j)(j, j) is a loop of length one and the algorithm finds it as a loop.

Example. Let n=7n = 7 and let the eight pairs be (2,5)(2,5), (1,4)(1,4), (4,6)(4,6), (2,4)(2,4), (5,7)(5,7), (3,5)(3,5), (6,7)(6,7), (1,3)(1,3). The pairs give a graph with the arrows 2→52 \to 5, 1→41 \to 4, and so on. There are 1515 rows of 1,…,71, \ldots, 7 that satisfy all eight pairs, found by trying all 50405040 orders. The run of Algorithm T below produces one of them.

Algorithms and programs

Algorithm 2.2.3T (topological sort, TAOCP Algorithm 2.2.3T). The input is nn and mm pairs (j,k)(j, k). The output is a row of all nn objects in which jj stands before kk for each pair, or the objects that lie on or after a loop when no such row exists.

Node: Algorithm 2.2.3T · Lean: not yet stated

The idea. Each object kk has a count, the number of pairs (j,k)(j, k) whose jj has not been written yet. An object with count 00 may be written. When an object is written, the algorithm subtracts 11 from the count of each of its successors. The objects of count 00 wait in a queue, so none is lost and none is taken twice.

The tables. COUNT[k][k] is the count of kk. For each jj there is a list TOP[j][j] of the pairs (j,k)(j, k), a linked stack of nodes with a field SUC (the object kk) and a field NEXT (the next node). The queue of free objects is linked through QLINK[k][k], which shares the word of COUNT[k][k]: an object enters the queue when its count is 00, so the word is free then. The cell QLINK[0]\mathrm{QLINK}[0] is the front F of the queue.

The steps.

T1: for k := 1 to n: COUNT[k] := 0; TOP[k] := null.   N := n.
T2: for each pair (j, k):
      COUNT[k] := COUNT[k] + 1
      take a node P; SUC(P) := k; NEXT(P) := TOP[j]; TOP[j] := P
T3: R := 0.
    for k := n down to 1:
      if COUNT[k] = 0: QLINK[R] := k; R := k
    F := QLINK[0]
T4: if F = 0 go to T7.
    write F.   N := N - 1.   P := TOP[F]
T5: while P is not null:
      k := SUC(P); COUNT[k] := COUNT[k] - 1
      if COUNT[k] = 0: QLINK[R] := k; R := k
      P := NEXT(P)
T6: F := QLINK[F]. go to T4.
T7: if N = 0 the row is complete.
    else the N objects with COUNT > 0 contain a loop.

Invariant. At the start of step T4, call the objects that have been written DD. Then: (i) N=n−∣D∣N = n - |D|; (ii) for each object kk not in DD, COUNT[k][k] is the number of pairs (j,k)(j, k) with j∉Dj \notin D; (iii) the queue, from F on to R, holds each object that is not in DD and has count 00, and no other object, and none twice.

Why it holds. After T3 the set DD is empty, (ii) is the definition of the counts, and the queue holds every object with count 00. In T5, the written object FF joins DD, and each pair (F,k)(F, k) lowers COUNT[k][k] by 11, which keeps (ii). An object enters the queue the moment its count becomes 00, which happens once, since the count only goes down, and objects of count 00 at the start entered in T3. The front object FF stays as the rear R while its successors enter, so the link QLINK[R][R] is valid. The count of a queued object stays 00, since every pair (j,k)(j, k) with jj written has been counted down, and jj is the only way down.

Correctness. If the algorithm ends with N=0N = 0, each object was written once, after all its predecessors, since an object enters the queue only when its count is 00, that is, when all its predecessors are in DD. If it ends with N>0N > 0, each of the NN remaining objects has COUNT >0> 0, hence a predecessor among the remaining objects. Following predecessors from one of them gives an endless chain in a finite set, so a pair of equal elements: a loop x1≺x2≺⋯≺x1x_1 \prec x_2 \prec \cdots \prec x_1. This is the argument of the Lemma, used the other way round. So the row is complete if and only if the pairs have no loop.

Run 1. The input is the example with n=7n = 7 and m=8m = 8 above. After T2 the counts are COUNT =[0,0,1,2,2,1,2]= [0, 0, 1, 2, 2, 1, 2] for the objects 1,…,71, \ldots, 7, and the lists are TOP[1]=(3,4)[1] = (3, 4), TOP[2]=(4,5)[2] = (4, 5), TOP[3]=(5)[3] = (5), TOP[4]=(6)[4] = (6), TOP[5]=(7)[5] = (7), TOP[6]=(7)[6] = (7), TOP[7]=()[7] = (). A newer pair goes before an older pair in the list. The scan of T3 runs from k=7k = 7 down to 11. It finds k=2k = 2 first and k=1k = 1 second, both with count 00, so the queue is 2,12, 1 with F =2= 2 and R =1= 1. The table shows the state after step T5 for each written object.

Written FF NN COUNT changes Queue after T5
2 6 COUNT[4] 2→12 \to 1, COUNT[5] 2→12 \to 1 1
1 5 COUNT[3] 1→01 \to 0, COUNT[4] 1→01 \to 0 3, 4
3 4 COUNT[5] 1→01 \to 0 4, 5
4 3 COUNT[6] 1→01 \to 0 5, 6
5 2 COUNT[7] 2→12 \to 1 6
6 1 COUNT[7] 1→01 \to 0 7
7 0 none empty

The output is 2 1 3 4 5 6 72\,1\,3\,4\,5\,6\,7 with N=0N = 0. Check: each of the eight pairs has its first element earlier in the row. In the row of F=1F = 1 the queue is 3,43, 4: the two objects entered when 11 was written. In the row of F=4F = 4 the queue is 5,65, 6: 66 entered at that moment and 55 was already waiting.

Run 2 (a loop). Let n=4n = 4 and let the pairs be (1,2)(1,2), (2,3)(2,3), (3,2)(3,2), (4,3)(4,3). The counts are COUNT =[0,2,2,0]= [0, 2, 2, 0], the scan of T3 finds 44 and then 11, and the queue is [4,1][4, 1].

Written FF NN COUNT changes Queue after T5
4 3 COUNT[3] 2→12 \to 1 1
1 2 COUNT[2] 2→12 \to 1 empty

The queue is empty with N=2N = 2. The two objects with count 11 are 22 and 33, and the pairs (2,3)(2,3) and (3,2)(3,2) form the loop. The output 4 14\,1 is a correct start of any row, but no row has 22 and 33.

Cost. T1 takes nn steps, T2 takes mm steps, T3 takes nn steps, and T4 to T6 take nn steps plus one step for each pair, since T5 visits each pair once, when its first object is written. The total is O(m+n)O(m + n), which cannot be improved since the algorithm must read each pair. The exact count for a MIX program is below.

Program 2.2.3T (Algorithm T in MIX, TAOCP Program 2.2.3T). The program uses these tables in memory. The cell NN holds nn in its (4:5)(4{:}5) field. PAIR is a table with one word per pair, with jj in (1:2)(1{:}2) and kk in (4:5)(4{:}5), ended by a word with j=0j = 0. The word X+kX + k holds COUNT or QLINK in (1:2)(1{:}2) and TOP in (4:5)(4{:}5). A node is a word with SUC in (1:2)(1{:}2) and NEXT in (4:5)(4{:}5), and the nodes lie at the addresses after X+nX + n. The row is written to the table OUT, ended with 00. The registers are rI1 =F= F, rI2 == the last node used, rI3 =R= R, rI4 =k= k, rI5 == a pointer into PAIR or OUT, rI6 =N= N.

Node: Program 2.2.3T · Lean: not yet stated

      LD6  NN(4:5)       N <- n
      ENT4 0,6
1H    STZ  X,4           COUNT[k] <- 0, TOP[k] <- null
      DEC4 1
      J4NN 1B            for k = n down to 0
      ENT2 X,6           the last node used is X + n
      ENT5 PAIR
2H    LD3  0,5(1:2)      j
      J3Z  4F            j = 0 ends the input
      LD4  0,5(4:5)      k
      LDA  X,4(COUNT)
      INCA 1
      STA  X,4(COUNT)    COUNT[k] <- COUNT[k] + 1
      INC2 1             new node
      LDA  X,3(TOP)
      STA  0,2(NEXT)     NEXT(P) <- TOP[j]
      ST4  0,2(SUC)      SUC(P) <- k
      ST2  X,3(TOP)      TOP[j] <- P
      INC5 1
      JMP  2B
4H    ENT4 0,6           k <- n
      ENT3 0             R <- 0
5H    LDA  X,4(COUNT)
      JANZ 6F
      ST4  X,3(QLINK)    QLINK[R] <- k
      ENT3 0,4           R <- k
6H    DEC4 1
      J4P  5B
      LD1  X(QLINK)      F <- QLINK[0]
      ENT5 OUT
7H    ST1  0,5(4:5)      write F
      J1Z  10F           F = 0 ends the output
      INC5 1
      DEC6 1             N <- N - 1
      LD2  X,1(TOP)      P <- TOP[F]
      J2Z  9F
8H    LD4  0,2(SUC)      k
      LDA  X,4(COUNT)
      DECA 1
      STA  X,4(COUNT)    COUNT[k] <- COUNT[k] - 1
      JANZ 8N
      ST4  X,3(QLINK)    QLINK[R] <- k
      ENT3 0,4           R <- k
8N    LD2  0,2(NEXT)     P <- NEXT(P)
      J2NZ 8B
9H    LD1  X,1(QLINK)    F <- QLINK[F]
      JMP  7B
10H   HLT

Notes on the program. The loop at 1H clears the cells X+nX + n down to X+0X + 0, which includes the front cell X+0X + 0. In the scan at 5H the object kk gets its QLINK only when its count is 00, so the field (1:2)(1{:}2) of X+kX + k is 00 and the last link of the queue is Λ\Lambda with no extra step. The program has no check for the overflow of PAIR or the node area, and it needs the nodes to fit above X+nX + n.

Time. Let aa be the number of objects with no predecessor. Counting each instruction with the times 2u2u for LD, ST and STZ and 1u1u for the other instructions gives these totals for a run that ends with N=0N = 0. The setup before 2H takes 4n+94n + 9. The input loop takes 21m+321m + 3. The scan of T3 takes 5n+3a+25n + 3a + 2. The output phase takes 14n+11m+6−3a14n + 11m + 6 - 3a. The sum is 32m+23n+2032m + 23n + 20, without the HLT, and aa cancels. The four phase formulas and the sum were checked on 300300 random inputs against a MIX model.

Run. For the example with n=7n = 7, m=8m = 8 and a=2a = 2 the phases take 3737, 171171, 4343 and 186186 units, in total 437=32⋅8+23⋅7+20437 = 32 \cdot 8 + 23 \cdot 7 + 20. The model gives the row 2 1 3 4 5 6 7 02\,1\,3\,4\,5\,6\,7\,0 in OUT.

Analysis C2.2.2.3.14 (the time of Program T, TAOCP Section 2.2.3). The time of Program T is 32m+23n+2032m + 23n + 20 units for an input without loops. The time is linear in mm and nn.

Node: 2.2.3-anal-T · Lean: not yet stated

Explanation. The loop of 2H runs mm times and costs 2121 units each. The loop of 8H runs once for each pair, and it costs 1111 units each, and the two loops give the term 32m32m. Each object costs 2323 units in the other phases. The formula has no term in aa and no term in the shape of the graph. For an input with a loop the output ends early, and the program stops with N>0N > 0 in rI6.

Example. A run on n=100n = 100 objects and m=300m = 300 pairs takes 32⋅300+23⋅100+20=11 92032 \cdot 300 + 23 \cdot 100 + 20 = 11\,920 units, in total time.

The exercises

The table has the 28 exercises of Section 2.2.3. The folder of X1 has no file for this section yet, and the Solution column says so. X1 does have files for Sections 2.2.1, 2.2.4 and 2.2.5.

Exercise Rating Markers Kind Lean Solution
2.2.3-1 10 not set not yet stated not in X1 yet
2.2.3-2 22 not set not yet stated not in X1 yet
2.2.3-3 22 not set not yet stated not in X1 yet
2.2.3-4 22 not set not yet stated not in X1 yet
2.2.3-5 24 not set not yet stated not in X1 yet
2.2.3-6 21 not set not yet stated not in X1 yet
2.2.3-7 23 not set not yet stated not in X1 yet
2.2.3-8 24 not set not yet stated not in X1 yet
2.2.3-9 20 not set not yet stated not in X1 yet
2.2.3-10 21 M not set not yet stated not in X1 yet
2.2.3-11 24 not set not yet stated not in X1 yet
2.2.3-12 20 M not set not yet stated not in X1 yet
2.2.3-13 48 M not set not yet stated not in X1 yet
2.2.3-14 21 M not set not yet stated not in X1 yet
2.2.3-15 25 M not set not yet stated not in X1 yet
2.2.3-16 22 M not set not yet stated not in X1 yet
2.2.3-17 21 not set not yet stated not in X1 yet
2.2.3-18 20 not set not yet stated not in X1 yet
2.2.3-19 18 not set not yet stated not in X1 yet
2.2.3-20 24 not set not yet stated not in X1 yet
2.2.3-21 21 not set not yet stated not in X1 yet
2.2.3-22 23 not set not yet stated not in X1 yet
2.2.3-23 27 not set not yet stated not in X1 yet
2.2.3-24 24 not set not yet stated not in X1 yet
2.2.3-25 47 not set not yet stated not in X1 yet
2.2.3-26 29 not set not yet stated not in X1 yet
2.2.3-27 25 not set not yet stated not in X1 yet
2.2.3-28 40 not set not yet stated not in X1 yet

Exercises 1 to 8 are on push, pop, subroutines, and the queue and deque variants of the linked method, with one on the inversion of a list. Do them first, with the tables of this chapter as a model. Exercises 9 to 16 are on partial orders and the embedding theorem. Exercises 17 to 25 are on Algorithm T and Program T, and the run above is the check for any change to the program. Exercises 26 and 27 are on the allocation of subroutine storage, and exercise 28 is on games.

Lean

The repository tamnd/taocp-lean has no declaration for Chapter 2, so nothing here is stated in Lean. A model of this section would need a memory as a function from addresses to nodes, with a chain of links, and the invariant of the pool as a statement that the free chain and the used chains are disjoint. The theorem of the embedding in a linear order is a statement about a finite strict order and a list, and it could be stated without any model of memory. No Mathlib name is claimed here.

Notes and history

The book credits A. B. Kahn, in 1962, for a technique like Algorithm T (Communications of the ACM 5, pages 558 to 562), and E. Szpilrajn, in 1930, for the proof that each partial order is contained in a linear order. The book also says that a better method for the sorting of partial orders is in Section 7.4.1. The three-link cycle of push and pop is a small fact that makes the proofs of correctness short: no link value is made or lost.

Section 2.2.3 of TAOCP gives the second way to store a list: each node holds a link to the next node, and the nodes can be anywhere in memory. The section builds on this idea in four steps. It first shows how a pool of free nodes serves all the lists of a program. It then redoes the stack and the queue with links, so that no list needs a fixed area. It then introduces partial orders, and it ends with Algorithm T, the topological sort, as a large example where many lists are made, read and destroyed together.

The chapter has one file. It explains the free-node stack AVAIL and the pool that grows into free memory, the push and pop of a linked stack with their MIX cost, the linked queue and its empty case, the definition of a partial order and the theorem that every finite partial order sits in a linear order, Algorithm T with its invariant and two hand runs, and Program T with its exact time 32m+23n+2032m + 23n + 20. Each run is a table of states that the reader can check by hand.

Read Section 2.2.2 first, because the chapter compares each linked operation with the sequential one. The X1 volume has no file for this section yet, so the exercise table says so.

The source of this page. Something is wrong? Report it.