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.

Using Heap Sort 401<br />

Heap sort dumps an unsorted list of data into the heap, always making sure<br />

the highest value appears in the root node. Then this highest value in the<br />

root node gets stored at the end of the list. Now the heap rearranges its<br />

values once more, putting the highest remaining value in the root node,<br />

repeating the process all over again, as shown in Figure 1-7.<br />

32 50 94 68 46<br />

Unsorted list<br />

50<br />

94<br />

68<br />

32<br />

32<br />

Remove highest value from root node<br />

and place at the end of the list.<br />

94<br />

46<br />

32<br />

Temporarily store data in a heap<br />

data structure where the root node<br />

contains the largest value.<br />

46<br />

50<br />

68<br />

Remove lowest node<br />

and move to the root node.<br />

32 50 94 68 46<br />

46<br />

50<br />

68<br />

32<br />

Swap values if the root node<br />

value is less than one of its<br />

child node values.<br />

46<br />

50<br />

32<br />

68<br />

Sorted list<br />

32 50 94 68 94<br />

Remove highest value from root node and<br />

place it in the last part of the unsorted list.<br />

Figure 1-7:<br />

Heap sort<br />

uses a tree<br />

data<br />

structure to<br />

sort and<br />

store items<br />

temporarily.<br />

32<br />

46<br />

50 32<br />

Swap values if the root node<br />

value is less than one of its<br />

child node values.<br />

46<br />

Swap values if the root node<br />

value is less than one of its<br />

child node values.<br />

32<br />

32<br />

32<br />

46<br />

32 46 50 68 94 Sorted list<br />

32 46 50 68 94 Final sorted list<br />

Sorted list<br />

50<br />

32 50 94 68 94<br />

Sorted list<br />

46<br />

32 50 50 68 94<br />

Book IV<br />

Chapter 1<br />

Sorting Algorithms

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

Saved successfully!

Ooh no, something went wrong!