#include #include "apvector.h" // // class node // standard binary tree node implementation // template class node { public: // constructors node (value_type & v, node *par, node *left, node *right) : val(v), parent(par), lchild(left), rchild(right) { } node (value_type & v): val(v), parent(NULL), lchild(NULL), rchild(NULL) {} // helper functions to return data members value_type value() { return val; } node *left(node *n1) { lchild=n1; return lchild; } node *left() { return lchild; } node *right(node *n1) { rchild=n1; return rchild; } node *right() { return rchild; } // Function to find size of tree at root int size() { int count=1; if (lchild !=0) count += lchild->size(); if (rchild != 0) count += rchild->size(); return count; }; // data members value_type val; node *parent; node *lchild; node *rchild; }; // // class skewHeap // heap priority queue implemented using skew heap merge // operations // template class skewHeap { public: skewHeap() : root(0) { }; ~skewHeap () { }; // priority queue protocol bool empty() { return root == 0; } int size() { return root->size(); } value_type top() { return root->value(); } void pop(); void push(value_type &value); void splice (skewHeap &secondHeap); protected: // root of heap node *root; // internal method to merge two heaps node *merge (node *, node *); }; void main() { // This main sorts the contents of a given array const int SIZE=10; int a[SIZE] = {3, 1, 52, 77, 22, 31, 100, 98, 13, 40}; int i; skewHeap H; char c; // print out the original array cout << endl << "The original numbers: "; for (i=0; i < SIZE; i++) cout << a[i] << " "; cout << endl << endl; // put the array into the heap for (i=0; i < SIZE; i++) H.push(a[i]); // take the elements off in order cout << "The sorted array: "; for (i=0; i> c; } // // remove the maximum element form the skew heap // // Pre Condition: the heap is not empty // Post Condition: the maximum element is no longer on the heap // template void skewHeap::pop () { assert (!empty()); node *top = root; root = merge(root->right(), root->left()); delete top; } // // put the new value from onto the heap by simply merging the // existing heap with a heap of one element. // // Pre Condition: the heap has been created // Post Condition: the given element added to the heap // template void skewHeap::push (value_type & val) { root = merge(root, new node(val)); } // // merge the two given heaps // // Pre Condition: the heaps have been created // Post Condition: a single heap with all the data from both heaps // template node *skewHeap::merge (node *h1, node *h2) { // If either heap is empty, return the non-empty heap if (!h1) return h2; if (!h2) return h1; // assume the largest is root of h1 if (h2->value() > h1->value()) return merge (h2, h1); // reverse children and recurse node *lchild = h1->left(); if (lchild) { h1->left(merge(h1->right(), h2)); h1->right(lchild); } else // no left child h1->left(h2); return h1; }