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

whereby after each step the next (least) item may be picked off the top of the heap. Once more, the<br />

question arises about where to store the emerging top elements <strong>and</strong> whether or not an in situ sort would be<br />

possible. Of course there is such a solution: In each step take the last component (say x) off the heap, store<br />

the top element of the heap in the now free location of x, <strong>and</strong> let x sift down into its proper position. The<br />

necessary n-1 steps are illustrated on the heap of Table 2.7. The process is described with the aid of the<br />

procedure sift as follows:<br />

R := n-1;<br />

WHILE R > 0 DO<br />

x := a[0]; a[0] := a[R]; a[R] := x;<br />

DEC(R); sift(1, R)<br />

END<br />

06 42 12 55 94 18 44 67<br />

12 42 18 55 94 67 44 | 06<br />

18 42 44 55 94 67 | 12 06<br />

42 55 44 67 94 | 18 12 06<br />

44 55 94 67 | 42 18 12 06<br />

55 67 94 | 44 42 18 12 06<br />

67 94 | 55 44 42 18 12 06<br />

94 | 67 55 44 42 18 12 06<br />

Table 2.7. Example of a HeapSort Process.<br />

The example of Table 2.7 shows that the resulting order is actually inverted. This, however, can easily<br />

be remedied by changing the direction of the ordering relations in the sift procedure. This results in the<br />

following procedure HeapSort. (Note that sift should actually be declared local to HeapSort.)<br />

PROCEDURE sift (L, R: INTEGER); (* ADenS2_Sorts *)<br />

VAR i, j: INTEGER; x: Item;<br />

BEGIN<br />

i := L; j := 2*i+1; x := a[i];<br />

IF (j < R) & (a[j] < a[j+1]) THEN j := j+1 END;<br />

WHILE (j 0 DO<br />

DEC(L); sift(L, R)<br />

END;<br />

WHILE R > 0 DO<br />

x := a[0]; a[0] := a[R]; a[R] := x;<br />

DEC(R); sift(L, R)<br />

END<br />

END HeapSort

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

Saved successfully!

Ooh no, something went wrong!