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

Shellsort that requires n 1.2 steps. Naturally, the task of bookkeeping has become more elaborate, <strong>and</strong><br />

therefore the complexity of individual steps is greater in the tree sort method; after all, in order to retain the<br />

increased amount of information gained from the initial pass, some sort of tree structure has to be created.<br />

Our next task is to find methods of organizing this information efficiently.<br />

12<br />

44<br />

12<br />

18<br />

44<br />

55<br />

12<br />

42<br />

94 18<br />

67<br />

Fig. 2.4. Selecting the least key<br />

12<br />

12<br />

18<br />

44<br />

12<br />

18<br />

67<br />

44<br />

55<br />

12<br />

42<br />

94<br />

18<br />

67<br />

Fig. 2.5. Refilling the holes<br />

Of course, it would seem particularly desirable to eliminate the need for the holes that in the end<br />

populate the entire tree <strong>and</strong> are the source of many unnecessary comparisons. Moreover, a way should be<br />

found to represent the tree of n items in n units of storage, instead of in 2n - 1 units as shown above. These<br />

goals are indeed achieved by a method called Heapsort by its inventor J. Williams [2-14]; it is plain that<br />

this method represents a drastic improvement over more conventional tree sorting approaches. A heap is<br />

defined as a sequence of keys h L , h L+1 , ... , h R (L ≥ 0) such that<br />

h i < h 2i+1 <strong>and</strong> h i < h 2i+2 for i = L ... R/2-1.<br />

If a binary tree is represented as an array as shown in Fig. 2.6, then it follows that the sort trees in Figs. 2.7<br />

<strong>and</strong> 2.8 are heaps, <strong>and</strong> in particular that the element h 0 of a heap is its least element:<br />

h 0 = min(h 0 , h 1 , ... , h n-1 )<br />

h 0<br />

h 1<br />

h 2<br />

h 3<br />

h 4<br />

h 5<br />

h 6<br />

h 7<br />

h 8<br />

h 9<br />

h 10<br />

h 11<br />

h 12<br />

h 13<br />

h 14<br />

Fig. 2.6. Array viewed as a binary tree<br />

h 0<br />

42<br />

06<br />

55 94<br />

18 12

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

Saved successfully!

Ooh no, something went wrong!