Espresso: A Concentrated Introduction to Java
Summary: In this laboratory, you will have an opportunity to enhance your understanding of heaps by working with an implementation of heaps.
Contents:
Required Code Files:
a. Create a package named
username.heaps.
b. Put
IntHeap.java and
IHTester.java
in that package.
A key issue in the implementation of heaps is how we are to compare the elements to determine whether one value is smaller than another (and, therefore, whether two values might potentially be swapped).
Explain how we might do such a comparison.
Make sure to do this exercise with at least one colleague!
As you may recall, the algorithm for get in heaps is
as follows:
The swap down
step is fairly straightforward: You determine
the value at the root of each subtree and, if the current value is
smaller, you swap with the smaller of the two values and recurse.
Unfortunately, it is less straightforward to find the rightmost leaf at the lowest level.
Sketch an algorithm that permits us to find the rightmost leaf at the lowest level.
Because of the problems with finding and deleting the rightmost leaf, heaps are often implemented by storing the tree in an array. Please read Storing Heaps in Arrays for more details.
a. This alternate implementation of heaps is partially coded as
the Java class
IntHeap.java.
Read through that code and determine what needs to be done to finish the implementation.
b. A tester for this class can be found in
IHTester.java.
Read through that code and explain what it does.
a. Sketch the series of heaps you expect to see when adding the values 4 2 1 5 2 0 to an empty heap.
b. Run IHTester and see if it creates the same heaps.
Run some additional tests to verify that the put
method behaves as you expect for small heaps.
As you may have observed, the get method does not
behave correctly because swapDown is unimplemented.
Implement it and test the modified program.
What happens if we try to put too many values into the heap (say, 18 values)?
Fix that problem.
Tuesday, 5 April 2005 [Samuel A. Rebelsky]
This page was generated by
Siteweaver on Thu Mar 30 15:24:37 2006.
The source to the page was last modified on Tue Apr 5 11:21:06 2005.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/Espresso/Labs/heaps.html.
You may wish to
validate this page's HTML
;
;
Check with Bobby