15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

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

402<br />

Using Heap Sort<br />

Initially, the heap sort algorithm may seem complicated because you need to<br />

create a heap data structure, copy and sort values among nodes, and delete<br />

nodes while you remove values and store them back in a sorted list.<br />

Although you can create a heap data structure by using a linked list, a much<br />

simpler method is to create a heap data structure by using an array, as<br />

shown in Figure 1-8.<br />

The first array element represents the root node, the next two elements represent<br />

the child nodes of the root, and so on. Rather than manipulate a<br />

linked list as a heap, it’s much simpler to rearrange values stored in an array,<br />

as shown in Figure 1-9. Because arrays are easy to implement in any <strong>programming</strong><br />

language, the heap sort algorithm is also easy to implement.<br />

Although slightly more complicated than bubble sort or selection sort, the<br />

heap sort algorithm offers faster per<strong>for</strong>mance.<br />

94<br />

Root node<br />

46<br />

74<br />

Level 1<br />

21<br />

32<br />

50<br />

68<br />

Level 2<br />

9 Level 3<br />

A heap<br />

Root node<br />

Figure 1-8:<br />

An array<br />

can mimic a<br />

heap data<br />

structure.<br />

94 46 74 21 32 50 68 9<br />

Level 1 Level 2 Level 3

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

Saved successfully!

Ooh no, something went wrong!