Question: The heap-delete (a, I) operation deletes the items in node I from the heap. For the maximum heap with n elements, provide the Implementation of heap-delete with the time of O (lgn.
Programming logic:
We can place the last heapsize element a [heapsize] In the heap to the node I position, and then reduce the heapsize by one. Then it involves heap adjustment to maintain the nature of the heap.
The adjustment is based on the relative size of the last element a [heapsize] and the element a [I] of the original I node. There are three situations:
(1) When a [heapsize] = A [I], the maximum heap does not need to be adjusted. Time Complexity: O (1)
(2) When a [heapsize] <A [I], the Subbranch heap with an I node as the root is damaged, and the heap remains unchanged elsewhere, therefore, you can directly call maxheapify (), a function that maintains the heap nature, to adjust the heap. The time complexity is O (lgn)
(3) When a [heapsize]> A [I], this is similar to the operation of "increasing the keyword value of an element in the priority queue to K", so you can directly call heapincreasekey () function. The time complexity is O (lgn)
ImplementationCodeAs follows:
// Heap adjustment, maintaining the heap nature void maxheapify (int * a, int I, int heapsize) {int largest = 0; int left = 0; int right = 0; int TMP = 0; If (left <= heapsize & A [I] <A [left]) {largest = left;} else {largest = I ;} if (right <= heapsize & A [Largest] <A [right]) {largest = right;} if (I! = Largest) {TMP = A [I]; A [I] = A [Largest]; A [Largest] = TMP; maxheapify (A, largest, heapsize );}} // increase the keyword value of element x in the heap to K. The value of K must be greater than the value of the original keyword void heapincreasekey (int * a, int X, int K) {int TMP = 0; If (k <A [x]) {return;} while (x> 1 & A [x> 1] <A [x]) {TMP = A [X]; A [x] = A [x> 1]; A [x> 1] = TMP; X >>=1 ;}} // Delete the specified ivoid heapdelete (int * a, int I, int * heapsize) {int TMP = A [* heapsize]; if (A [I] = TMP) {(* heapsize) --;} else if (a [I]> TMP) // After the I node is changed to a small TMP node, the maximum heap nature of the branch may be damaged. You need to adjust {A [I] = TMP; (* heapsize) --; maxheapify (A, I, * heapsize );} else if (a [I]> TMP) // The value of the I node is increased to a larger TMP {(* heapsize) --; heapincreasekey (A, I, TMP );}} int main () {return 0 ;}