delMax() api - Priority Queue

470 Views Asked by At

In the lecture from Sedgewick,

below is the java code, for deleting max element from heap,

enter image description here

Question:

If I consider line, exch(1, N--), why to decrement N after swapping? Again he access right index with +1 to loiter in pq[N+1] = null for loitering. I see code as,

public Key delMax(){
  Key max = pq[1];
  exch(1, N);
  sink(1);
  pq[N] = null;
  return max;
}
2

There are 2 best solutions below

1
On

It should be obvious that, if you delete something, you now have fewer things. With your changes, N stays the same.

0
On

You haven't given enough context to know, but my guess would be that N is an instance variable (field) of the class that is also used by sink(), so your rewrite might not be equivalent.

You can always try it and see: you can test his version and your version and see if they do the same thing.