25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 65<br />

As an example, if the middle key 42 is selected as compar<strong>and</strong> x, then the array of keys<br />

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

requires the two exchanges 18 ↔ 44 <strong>and</strong> 6 ↔ 55 to yield the partitioned array<br />

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

<strong>and</strong> the final index values i = 4 <strong>and</strong> j = 2. Keys a 0 ... a i-1 are less or equal to key x = 42, <strong>and</strong> keys<br />

a j+1 ... a n-1 are greater or equal to key x. Consequently, there are three parts, namely<br />

Ak: 1 ≤ k < i :<br />

Ak: i ≤ k ≤ j :<br />

Ak: j < k ≤ n-1 :<br />

a k ≤ x<br />

a k ? x<br />

x ≤ a k<br />

The goal is to increase i <strong>and</strong> decrease j, so that the middle part vanishes. This algorithm is very<br />

straightforward <strong>and</strong> efficient because the essential compar<strong>and</strong>s i, j <strong>and</strong> x can be kept in fast registers<br />

throughout the scan. However, it can also be cumbersome, as witnessed by the case with n identical keys,<br />

which result in n/2 exchanges. These unnecessary exchanges might easily be eliminated by changing the<br />

scanning statements to<br />

WHILE a[i]

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

Saved successfully!

Ooh no, something went wrong!