0

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;
}
overexchange
  • 15,768
  • 30
  • 152
  • 347

2 Answers2

0

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.

D.W.
  • 3,382
  • 7
  • 44
  • 110
0

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

Jim Balter
  • 16,163
  • 3
  • 43
  • 66