Professional Documents
Culture Documents
PPT9 - Heap and Deap
PPT9 - Heap and Deap
• Heap Sort
An O(n.lg(n)) algorithm.
Heap for Priority Queue
• Heap is an efficient implementation of priority queue
data structure.
• ROOT
int findmin() {
return data[1];
}
Insertion in Min-Heap
• We would like to insert a new element into the heap,
but we should maintain its heap property.
• (continue)
Deletion in Min-Heap
• (continue)
Heap Complexity
• find-min : O(1)
• insert : O(log(n))
• delete-min : O(log(n))
• Upheapmax
Compare current node’s value with its grand-parent’s value.
If the current node’s value is larger than its parent’s than
swap their values and continue upheapmax the grand-
parent node.
Deletion in Min-Max
Heap
• Deletion of the smallest element
Replace root with the last element in heap.
Decrease the number of element in heap.
Downheapmin from root.
• Insert (50)
Example of Insertion in
Deap
• max-upheap
Example of Insertion in
Deap
• Deap after
• insertion of 50
Deletion in Deap
• Delete-min in Deap:
• First store the last element of deap in T and decrease the number
of element in deap.
• Transform the deletion of root of min heap into deletion of leaf of
min heap by shifting vacancy at the root of the min heap to the
leaf node (in each level, proceed to node with smaller value).
Repeat until we arrive at leaf node (x).
• Compute y = max-partner(x).
• If y’s value is larger than T, no swap needed, insert T at x’s
position. Otherwise, swap y’s value with T and insert y’s value
(now T) at x’s position.
• Upheap the inserted node.
Deletion in Deap
• Delete-max in Deap:
• Similar to delete-min except when finding the min-partner we
instead find the largest element in min-partner sub-tree (should
be located on one of min-partner sub-tree leaves)
Example of Deletion in
Deap
• delete-min()
Example of Deletion in
Deap
• (continue)
Example of Deletion in
Deap
• (continue)
Example of Deletion in
Deap