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

≤<br />

≥<br />

L<br />

k<br />

Fig. 2.10. Bound x too large<br />

j<br />

i<br />

R<br />

3. j < k < i: the element a k splits the array into two partitions in the specified proportions <strong>and</strong> therefore<br />

is the desired quantile (see Fig. 2.11).<br />

≤<br />

≥<br />

L<br />

Fig. 2.11. Correct bound<br />

j k i<br />

R<br />

The splitting process has to be repeated until case 3 arises. This iteration is expressed by the following<br />

piece of program:<br />

L := 0; R := n;<br />

WHILE L < R-1 DO<br />

x := a[k];<br />

partition (a[L] ... a[R-1]);<br />

IF j < k THEN L := i END;<br />

IF k < i THEN R := j END<br />

END<br />

For a formal proof of the correctness of this algorithm, the reader is referred to the original article by<br />

Hoare. The entire procedure Find is readily derived from this.<br />

PROCEDURE Find (k: INTEGER); (* ADenS2_Sorts *)<br />

(*reorder a such that a[k] is k-th largest*)<br />

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

BEGIN<br />

L := 0; R := n-1;<br />

WHILE L < R-1 DO<br />

x := a[k]; i := L; j := R;<br />

REPEAT<br />

WHILE a[i] < x DO i := i+1 END;<br />

WHILE x < a[j] DO j := j-1 END;<br />

IF i j;<br />

IF j < k THEN L := i END;<br />

IF k < i THEN R := j END<br />

END<br />

END Find<br />

If we assume that on the average each split halves the size of the partition in which the desired quantile<br />

lies, then the number of necessary comparisons is<br />

n + n/2 + n/4 + ... + 1 ≈ 2n

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

Saved successfully!

Ooh no, something went wrong!