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

Fig. 2.7. Heap with 7 elements<br />

06<br />

42<br />

12<br />

55 94<br />

18 44<br />

Fig. 2.8. Key 44 sifting through the heap<br />

Let us now assume that a heap with elements h L+1 ... h R is given for some values L <strong>and</strong> R, <strong>and</strong> that a<br />

new element x has to be added to form the extended heap h L ... h R . Take, for example, the initial heap h 1<br />

... h 7 shown in Fig. 2.7 <strong>and</strong> extend the heap to the left by an element h 0 = 44. A new heap is obtained by<br />

first putting x on top of the tree structure <strong>and</strong> then by letting it sift down along the path of the smaller<br />

compar<strong>and</strong>s, which at the same time move up. In the given example the value 44 is first exchanged with 06,<br />

then with 12, <strong>and</strong> thus forming the tree shown in Fig. 2.8. We now formulate this sifting algorithm as<br />

follows: i, j are the pair of indices denoting the items to be exchanged during each sift step. The reader is<br />

urged to convince himself that the proposed method of sifting actually preserves the heap invariants that<br />

define a heap.<br />

A neat way to construct a heap in situ was suggested by R. W. Floyd. It uses the sifting procedure<br />

shown below. Given is an array h 0 ... h n-1 ; clearly, the elements h m ... h n-1 (with m = n DIV 2) form a<br />

heap already, since no two indices i, j are such that j = 2i+1 or j = 2i+2. These elements form what may<br />

be considered as the bottom row of the associated binary tree (see Fig. 2.6) among which no ordering<br />

relationship is required. The heap is now extended to the left, whereby in each step a new element is<br />

included <strong>and</strong> properly positioned by a sift. This process is illustrated in Table 2.6 <strong>and</strong> yields the heap<br />

shown in Fig. 2.6.<br />

PROCEDURE sift (L, R: INTEGER);<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+1] < a[j]) THEN j := j+1 END;<br />

WHILE (j 0 DO DEC(L); sift(L, n-1) END<br />

In order to obtain not only a partial, but a full ordering among the elements, n sift steps have to follow,

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

Saved successfully!

Ooh no, something went wrong!