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 84<br />

IF L < N THEN k1 := L ELSE k1 := N END;<br />

K1 := k1;<br />

FOR i := 0 TO k1-1 DO (*set input riders*)<br />

Runs.Set(r[i], g[i])<br />

END;<br />

FOR i := 0 TO k1-1 DO (*set output riders*)<br />

g[i] := Files.New(""); Files.Set(w[i], g[i], 0)<br />

END;<br />

(*merge from r[0] ... r[k1-1] to w[0] ... w[K1-1]*)<br />

FOR i := 0 TO k1-1 DO t[i] := i END;<br />

L := 0; (*nof runs merged*)<br />

j := 0;<br />

REPEAT (*merge on run from inputs to w[j]*)<br />

INC(L); k2 := k1;<br />

REPEAT (*select the minimal key*)<br />

m := 0; min := r[t[0]].first; i := 1;<br />

WHILE i < k2 DO<br />

x := r[t[i]].first;<br />

IF x < min THEN min := x; m := i END;<br />

INC(i)<br />

END;<br />

Runs.copy(r[t[m]], w[j]);<br />

IF r[t[m]].eof THEN (*eliminate this sequence*)<br />

DEC(k1); DEC(k2);<br />

t[m] := t[k2]; t[k2] := t[k1]<br />

ELSIF r[t[m]].eor THEN (*close run*)<br />

DEC(k2);<br />

tx := t[m]; t[m] := t[k2]; t[k2] := tx<br />

END<br />

UNTIL k2 = 0;<br />

INC(j);<br />

IF j = K1 THEN j := 0 END<br />

UNTIL k1 = 0<br />

UNTIL L = 1;<br />

RETURN g[0]<br />

END BalancedMerge

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

Saved successfully!

Ooh no, something went wrong!