Data Str & Algorithm HW Solutions 36

Data Str& - int rightchild(int pos const return 2*pos 2 Return rightchild pos int parent(int pos const Return parent position

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

View Full Document Right Arrow Icon
36 Chap. 5 Binary Trees 5.18 (a) The array will take on the following order: 653421 The value 7 will be at the end of the array. (b) The array will take on the following order: 746321 The value 5 will be at the end of the array. 5.19 // Min-heap class template <class Elem, class Comp> class minheap { private: Elem* Heap; // Pointer to the heap array int size; // Maximum size of the heap int n; // # of elements now in the heap void siftdown(int); // Put element in correct place public: minheap(Elem* h, int num, int max) // Constructor { Heap = h; n = num; size = max; buildHeap(); } int heapsize() const // Return current size { return n; } bool isLeaf(int pos) const // TRUE if pos a leaf { return (pos >= n/2) & (pos < n); } int leftchild(int pos) const { return 2*pos + 1; } // Return leftchild pos
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: int rightchild(int pos) const { return 2*pos + 2; } // Return rightchild pos int parent(int pos) const // Return parent position { return (pos-1)/2; } bool insert(const Elem&); // Insert value into heap bool removemin(Elem&); // Remove maximum value bool remove(int, Elem&); // Remove from given pos void buildHeap() // Heapify contents { for (int i=n/2-1; i>=0; i--) siftdown(i); } }; template <class Elem, class Comp> void minheap<Elem, Comp>::siftdown(int pos) { while (!isLeaf(pos)) { // Stop if pos is a leaf int j = leftchild(pos); int rc = rightchild(pos); if ((rc < n) && Comp::gt(Heap[j], Heap[rc])) j = rc; // Set j to lesser child’s value if (!Comp::gt(Heap[pos], Heap[j])) return; // Done...
View Full Document

This note was uploaded on 12/27/2011 for the course MAP 2302 taught by Professor Bell,d during the Fall '08 term at UNF.

Ask a homework question - tutors are online