In the lecture from Sedgewick,
below is the java code, for deleting max element from heap,
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;
}
It should be obvious that, if you delete something, you now have fewer things. With your changes, N stays the same.