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.

400<br />

Using Heap Sort<br />

The two criteria <strong>for</strong> storing data in a heap are that<br />

✦ Every parent node must contain a value greater than either of its<br />

child nodes.<br />

✦ The tree must fill each level be<strong>for</strong>e adding nodes to the next lower level.<br />

If there aren’t enough nodes to fill out an entire level, the nodes must fill<br />

out as much of the last level as possible, starting from the left.<br />

Figure 1-6 shows a valid heap and two invalid heaps.<br />

The heap sort algorithm works like this:<br />

1. Store an unsorted list in a heap data structure, which sorts data so the<br />

highest values appear near the top of the heap.<br />

2. Yank off the highest value stored in the root node and store this value<br />

as the end of the sorted list.<br />

3. Re-sort the heap so the highest values appear near the top of the heap.<br />

4. Repeat Steps 2 and 3 until all values have been removed from the<br />

heap and sorted.<br />

94<br />

32<br />

46 74 Levels<br />

46<br />

9<br />

21<br />

32<br />

50<br />

68<br />

21<br />

94<br />

50<br />

68<br />

9<br />

A heap<br />

74<br />

Not a heap since not every<br />

parent node value is greater<br />

than its child node values.<br />

32<br />

Figure 1-6:<br />

Valid and<br />

invalid heap<br />

binary trees.<br />

74<br />

21<br />

46<br />

94<br />

50<br />

9<br />

68<br />

Not a heap since earlier<br />

levels are not full.

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

Saved successfully!

Ooh no, something went wrong!