Q. I’m still not clear on the purpose of priority queues. Why exactly don’t we just sort
and then consider the items in increasing order in the sorted array?
A. In some data-processing examples such as TopM and Multiway, the total amount of
data is far too large to consider sorting (or even storing in memory). If you are looking
for the top ten entries among a billion items, do you really want to sort a billion-entry
array? With a priority queue, you can do it with a ten-entry priority queue. In other examples,
all the data does not even exist together at any point in time: we take something
from the priority queue, process it, and as a result of processing it perhaps add some
more things to the priority queue.
Q. Why not use Comparable, as we do for sorts, instead of the generic Item in MaxPQ?
A. Doing so would require the client to cast the return value of delMax() to an actual
type, such as String. Generally, casts in client code are to be avoided.
Q. Why not use a[0] in the heap representation?
A. Doing so simplifies the arithmetic a bit. It is not difficult to implement the heap
methods based on a 0-based heap where the children of a[0] are a[1] and a[2], the
children of a[1] are a[3] and a[4], the children of a[2] are a[5] and a[6], and
so forth, but most programmers prefer the simpler arithmetic that we use. Also, using
a[0] as a sentinel value (in the parent of a[1]) is useful in some heap applications.
Q. Building a heap in heapsort by inserting items one by one seems simpler to me than
the tricky bottom-up method described on page 323 in the text. Why bother?
A. For a sort implementation, it is 20 percent faster and requires half as much tricky
code (no swim() needed). The difficulty of understanding an algorithm has not necessarily
much to do with its simplicity, or its efficiency.
Q. What happens if I leave off the extends Comparable phrase in an implementation
like MaxPQ ?
A. As usual, the easiest way for you to answer a question of this sort for yourself is to
simply try it. If you do so for MaxPQ you will get a compile-time error:
MaxPQ.java:21: cannot find symbol
symbol : method compareTo(Item)
which is Java’s way of telling you that it does not know about compareTo() in Item
because you neglected to declare that Item extends Comparable.