Search code examples
algorithmdata-structuresheappseudocodeperformance

Deleting in a heap, why does this implementation switch the values of the last element, not just replace it?


(USC CSCI 303 Homework 4) Problem 7 (6.5-7):

The operation Heap-Delete(A, i) deletes the item in node i from heap A. Give an implementation of Heap-Delete that runs in O(lg n) time for an n-element max-heap.

here's the pseudo-code and description of the reference solution:

Heap-Delete(A, i)
    A[i] ↔ A[length(A)] 
    length(A) ← length(A) - 1
    Heapify(A, i)

The algorithm deletes the element at node i, and replaces it with the last element. Then the algorithm runs Heapify from the node i.

isn't it better if "↔" was "←" instead? or is this really necessary?

I got this from http://www-scf.usc.edu/~csci303/cs303hw4solutions.pdf (Page 4)


Solution

  • Perhaps this is done so that Heap-Delete() can be called repeatedly during execution of a heapsort. In heapsort, the largest item is taken off the heap, stashed in the last item of the heap, and the heap size is decreased by one. Then the heap is re-heapified, and you proceed to the next largest item. The end result, when the heap is size 1, is that the array on which the heap is/was based is sorted from smallest to largest. Writing Heap-Delete() in this way allows Heap-Sort() to be very simple:

    while (HeapSize>0)
       HeapDelete(0)
    

    Now it doesn't look like your Heap-Delete() keeps track of heap size outside of length, which might be evidence against my theory. But this is my best guess anyway.