lab_heaps2 Happy Heaps

Assignment Description

In this lab you will write some heap functions to implement a min heap from scratch.

The version of heap you will implement will have a tree implemented in an array. Your array can be 0-index or 1-indexed, where 0 and 1 are the indices of the root, depending on which one you choose.

The left and right children of the root will be at the positions immediately after the root. For example, if your root is at index 0, its left child will be at index 1 and 2. The root’s left children will be at positions 3 and 4, and the root’s right children will be at positions 5 and 6, and so on and so forth. You will need to determine the indices to store these children in leftChild() and rightChild(), and the indices of each element’s parent in parent().

Remember that the big idea about a heap is that it must keep its heap property. In a min heap, this means that each element is smaller than both of its children. A max heap is the opposite- each element is larger than both of its children. Your maxPriorityChild() function will return the min child (out of an element’s left and right children) in a min heap and the max child in a max heap. This is not a recursive function- it simply utilizes the higherPriority functor and returns whichever child out of the two is less than or greater than the other, depending on what the priority for this heap is. Your heapifyUp() and heapifyDown() functions will ensure the heap property of your heap, by swapping elements recursively up or down the tree to maintain the heap property.

Checking Out The Code

We hope you know by now, but please run svn up in your cs225
directory and work in lab_heaps2.

hasAChild()

maxPriorityChild()

heapifyDown()

Doxygen for heapifyDown().
Maintains heap property by “sinking” a node down. When we pop an element, we heapifyDown() the new root so the heap’s property is maintained.

heapifyUp()

Maintains heap property by “bubbling” a node up. When a node is added to the end of the array, we call heapifyUp() to recursively swap it into its proper place.
We have written this for you as an example: Doxygen for heapifyUp().

Testing Your Code

You can test your implementation by running:

./testheap // Runs testheap. You can diff the output with soln_testheap.out
./testheap color // colorizes the output of testheap (green for correct output
// red for incorrect output, or red underlines for missing output)
./testheap > out.txt // Redirects the output to the file "out.txt" so you can diff it with soln_testheap.out
./testheap 10000 // Tests your heap with 10000 items instead of the default 15
make test // Tests your heapify and constructor

Grading Information

The following files (and ONLY those files!!) are used for grading this lab:

heap.cpp

heap.h

If you modify any other files, they will not be grabbed for grading! And you will be sad, and we will be apathetic!