25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 91<br />

from all sources with d i = 0, <strong>and</strong> d i is decremented for all other sequences, indicating that one dummy run<br />

was taken off. We denote the number of input sequences involved in a merge by k.<br />

4. It is impossible to derive termination of a phase by the end-of status of the N-1'st sequence, because<br />

more merges might be necessary involving dummy runs from that source. Instead, the theoretically<br />

necessary number of runs is determined from the coefficients a i . The coefficients a i were computed during<br />

the distribution phase; they can now be recomputed backward.<br />

The main part of the Polyphase Sort can now be formulated according to these rules, assuming that all<br />

N-1 sequences with initial runs are set to be read, <strong>and</strong> that the tape map is initially set to t i = i.<br />

REPEAT (*merge from t[0] ... t[N-2] to t[N-1]*)<br />

z := a[N-2]; d[N-1] := 0;<br />

REPEAT (*merge one run*)<br />

k := 0;<br />

(*determine no. of active sequences*)<br />

FOR i := 0 TO N-2 DO<br />

IF d[i] > 0 THEN<br />

DEC(d[i])<br />

ELSE<br />

ta[k] := t[i]; INC(k)<br />

END<br />

END;<br />

IF k = 0 THEN<br />

INC(d[N-1])<br />

ELSE merge one real run from t[0] ... t[k-1] to t[N-1]<br />

END;<br />

DEC(z)<br />

UNTIL z = 0;<br />

Runs.Set(r[t[N-1]], f[t[N-1]]);<br />

rotate sequences in map t;<br />

compute a[i] for next level;<br />

DEC(level)<br />

UNTIL level = 0<br />

(*sorted output is f[t[0]]*)<br />

The actual merge operation is almost identical with that of the N-way merge sort, the only difference<br />

being that the sequence elimination algorithm is somewhat simpler. The rotation of the sequence index map<br />

<strong>and</strong> the corresponding counts d i (<strong>and</strong> the down-level recomputation of the coefficients a i ) is<br />

straightforward <strong>and</strong> can be inspected in the following program that represents the Polyphase algorithm in its<br />

entirety.<br />

PROCEDURE Polyphase (src: Files.File): Files.File; (* ADenS24_MergeSorts *)<br />

VAR i, j, mx, tn: INTEGER;<br />

k, dn, z, level: INTEGER;<br />

x, min: INTEGER;<br />

a, d: ARRAY N OF INTEGER;<br />

t, ta: ARRAY N OF INTEGER; (*index maps*)<br />

R: Runs.Rider; (*source*)<br />

f: ARRAY N OF Files.File;<br />

r: ARRAY N OF Runs.Rider;<br />

PROCEDURE select;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!