10b - TreesSlides

# We start at the bottom making each subtree a heap

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: htly larger dataset. 3, 7, 4, 2, 7, 8, 5, 1 (a duplicate too.) 3 8 values, so the last parent is nlast = 3. nlast The subtree with that as root is a heap. Proceed to node 2. A non-heap. Parent 4 has children 8 and 5. nonSwap 4 and 8. 3 0 0 7 4 7 1 2 1 4 2 2 7 8 5 2 7 8 5 3 4 5 6 3 4 5 6 1 7 1 node number 7 18 Of course, such a move may cause a subtree to be no longer a heap. That's why we have to recheck all subtrees recursively. (Not needed here.) So we move to node 1. It's a heap. And finally to the root. We swap the 3 for the larger of its children - the 8. 3 3 0 0 7 8 7 1 2 1 2 7 4 5 3 4 5 6 8 2 2 5 4 5 6 1 7 4 3 1 7 7 Now node 2 is not a heap. Swap 3 and 5, the larger of its children. Now node 2 is not a heap. Swap 3 and 5, the larger of its children. And we’re finished. We have a heap. 8 8 0 0 7 3 7 1 2 1 5 2 2 7 4 5 2 7 4 3 3 4 5 6 3 4 5 6 1 1 7 7 Let's see what the code looks like. Assume the following data items (for an integer data set). int n, nlast; nlast; int* value; // dynamic array Here's the code to make a heap provided that each sub...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online