Algorithms and Data Structures
Algorithms and Data Structures
Algorithms and Data Structures
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 175<br />
The details of the refinement of the statement in italics can be found in the program presented below. The<br />
average path length of T 0,n is now given by the quotient p 0,n /w 0,n , <strong>and</strong> its root is the node with index r 0,n .<br />
Let us now describe the structure of the program to be designed. Its two main components are the<br />
procedures to find the optimal search tree, given a weight distribution w, <strong>and</strong> to display the tree given the<br />
indices r. First, the counts a <strong>and</strong> b <strong>and</strong> the keys are read from an input source. The keys are actually not<br />
involved in the computation of the tree structure; they are merely used in the subsequent display of the tree.<br />
After printing the frequency statistics, the program proceeds to compute the path length of the perfectly<br />
balanced tree, in passing also determining the roots of its subtrees. Thereafter, the average weighted path<br />
length is printed <strong>and</strong> the tree is displayed.<br />
In the third part, procedure OptTree is activated in order to compute the optimal search tree; thereafter,<br />
the tree is displayed. And finally, the same procedures are used to compute <strong>and</strong> display the optimal tree<br />
considering the key frequencies only, ignoring the frequencies of non-keys. To summarize, the following are<br />
the global constants <strong>and</strong> variables:<br />
CONST N = 100; (*max no. of keywords*) (* ADenS46_OptTree *)<br />
WordLen = 16; (*max keyword length*)<br />
VAR key: ARRAY N+1, WordLen OF CHAR;<br />
a, b: ARRAY N+1 OF INTEGER;<br />
p, w, r: ARRAY N+1, N+1 OF INTEGER;<br />
PROCEDURE BalTree (i, j: INTEGER): INTEGER;<br />
VAR k, res: INTEGER;<br />
BEGIN<br />
k := (i+j+1) DIV 2; r[i, j] := k;<br />
IF i >= j THEN res := 0<br />
ELSE res := BalTree(i, k-1) + BalTree(k, j) + w[i, j]<br />
END;<br />
RETURN res<br />
END BalTree;<br />
PROCEDURE ComputeOptTree (n: INTEGER);<br />
VAR x, min, tmp: INTEGER;<br />
i, j, k, h, m: INTEGER;<br />
BEGIN<br />
(*argument: w, results: p, r*)<br />
FOR i := 0 TO n DO p[i, i] := 0 END;<br />
FOR i := 0 TO n-1 DO<br />
j := i+1; p[i, j] := w[i, j]; r[i, j] := j<br />
END;<br />
FOR h := 2 TO n DO<br />
FOR i := 0 TO n-h DO<br />
j := i+h; m := r[i, j-1]; min := p[i, m-1] + p[m, j];<br />
FOR k := m+1 TO r[i+1, j] DO<br />
tmp := p[i, k-1]; x := p[k, j] + tmp;<br />
IF x < min THEN m := k; min := x END<br />
END;<br />
p[i, j] := min + w[i, j]; r[i, j] := m<br />
END<br />
END<br />
END ComputeOptTree;