next up previous
Next: About this document Up: Assignment 9: Heaps Previous: Clean up the sorters

Implement a heap

  1. Write an implementation of a tree using a Vector. It should include methods named left, right and parent as described in the book. You can include a vector as an instance variable or inherit from the Vector class, whichever you prefer.

    HINT: you might want to put a dummy value into the vector to occupy the zero-eth space, which the tree implementation does not use.

  2. Write an implementation of a Heap using your implementation of a tree. I wrote remove recursively, as shown in the book, using reheapify as a helper method. You can also write insert recursively, but I ended up doing it iteratively. It's up to you.
  3. Write a print method for the Heap class. It should print the contents of the Heap in a nice form: in level order, with each level on a different line. You might find this useful for debugging insert and remove.
  4. Write a method in Sort called heapSort that sorts an array of ints by traversing the array, putting all the ints into a heap, and then pulling the ints out of the heap (in descending order) and putting them back in the array.

    WARNING: heapSort will often work correctly even if reheapify is not correct. Make sure you check your remove method carefully. You might want to try some additional tests.

  5. Compare the run time of heapSort to the run-time of the other sort algorithms.



Allen Downey
Mon Nov 13 09:09:05 EST 2000