Assume the following data items for an integer data

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

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: tree is already a heap. void MakeHeap(int node) { int curr, child, temp; curr = node; if (node <= nlast) // if there's a child { child = 2*node+1; if (value[node] < value[child]) node = child; child++; // is there a right child? if (child < n && value[node] < value[child]) node = child; } (node is now the element containing the largest of the values in the node and its children.) 19 if (node != curr) // not a heap { temp = value[node]; value[node] = value[curr]; value[curr] = temp; MakeHeap(node); } We can ensure that the subtrees are all heaps by checking them, starting from the bottom. Of course the last subtree is from node nlast. nlast } So the following code will do the whole task. Note the recursion to check the subtree now that its root has been altered. But wait, there's more. for (node=nlast;node>=0;node--) (node=nlast;node>=0;node--) MakeHeap(node); Here's our previous example. We exchange the first and last values. Since this procedure puts the largest at the root, we can use it to sort the data. 8 It's called Heapsort. It...
View Full Document

Ask a homework question - tutors are online