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

PROCEDURE B (k: INTEGER);<br />

BEGIN<br />

IF k > 0 THEN<br />

B(k-1); Draw.line(5, h); C(k-1); Draw.line(6, 2*h);<br />

A(k-1); Draw.line(7, h); B(k-1)<br />

END<br />

END B;<br />

PROCEDURE C (k: INTEGER);<br />

BEGIN<br />

IF k > 0 THEN<br />

C(k-1); Draw.line(3, h); D(k-1); Draw.line(4, 2*h);<br />

B(k-1); Draw.line(5, h); C(k-1)<br />

END<br />

END C;<br />

PROCEDURE D (k: INTEGER);<br />

BEGIN<br />

IF k > 0 THEN<br />

D(k-1); Draw.line(1, h); A(k-1); Draw.line(2, 2*h);<br />

C(k-1); Draw.line(3, h); D(k-1)<br />

END<br />

END D;<br />

PROCEDURE Sierpinski* (n: INTEGER);<br />

CONST SquareSize = 512;<br />

VAR i, x0, y0: INTEGER;<br />

BEGIN<br />

Draw.Clear;<br />

h := SquareSize DIV 4;<br />

x0 := Draw.width DIV 2; y0 := Draw.height DIV 2 + h;<br />

i := 0;<br />

REPEAT<br />

INC(i); x0 := x0-h;<br />

h := h DIV 2; y0 := y0+h; Draw.Set(x0, y0);<br />

A(i); Draw.line(7,h); B(i); Draw.line(5,h);<br />

C(i); Draw.line(3,h); D(i); Draw.line(1,h)<br />

UNTIL i = n<br />

END Sierpinski.<br />

The elegance of the use of recursion in these exampes is obvious <strong>and</strong> convincing. The correctness of the<br />

programs can readily be deduced from their structure <strong>and</strong> composition patterns. Moreover, the use of an<br />

explicit (decreasing) level parameter guarantees termination since the depth of recursion cannot become<br />

greater than n. In contrast to this recursive formulation, equivalent programs that avoid the explicit use of<br />

recursion are extremely cumbersome <strong>and</strong> obscure. Trying to underst<strong>and</strong> the programs shown in [3-3]<br />

should easily convince the reader of this.

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

Saved successfully!

Ooh no, something went wrong!