You are on page 1of 28

Min Heap and Max Heap

By Ali Saeed
Definition
• A binary heap is a complete binary tree which
satisfies the heap ordering property. The
ordering can be one of two types:
– The min-heap property: the value of each node is
greater than or equal to the value of its parent,
with the minimum-value element at the root.
– The max-heap property: the value of each node is
less than or equal to the value of its parent, with
the maximum-value element at the root.
Application of Heap
• Min Heap and Max Heap are used to
implement a priority queue.
Examples
Development of Max-Heap
• Data: 15,7,12,28,36,1,37,13,4,25,3,9,27,2,5,16
Next Steps
Next Step
Next Step
Next Step
Class Exercise
• Develop Min-Heap of the following data:
• 13, 5 , 33, 90, 100, 10, 22, 18, 11, 43, 1
Class Exercise
• Develop Max-Heap of the following data:

• 10, 22, 18, 11, 43,1, 13, 5 , 33, 18, 90, 12


Insertion Data in Min Heap
• In Min Heap, minimum value is always on the
top
– Initially, the value is inserted at available place of
a complete binary tree.
– Next, the value is compared with the parent node
value. If the parent contain larger value, then the
nodes will be swaped.
Example of Insertion
Final Insertion
Class Exercise
• Insert -3 in previously developed Min-Heap
Delete data from Min heap
Another example of deletion
Array implementation of Heap
• The root is the second item in the array. We
skip the index zero cell of the array for the
convenience of implementation. Consider k-th
element of the array, the
– its left child is located at 2*k index
– its right child is located at 2*k+1. index
– its parent is located at k/2 index
Cont…

its left child is located at 2*k index


its right child is located at 2*k+1. index
its parent is located at k/2 index
Class Exercise

Parent of K?
Left Child of G?
Right Child of K?
Class Exercise
On which array index ,the right child of K will be stored?
Class Exercise
On which array index ,the right child of B will be stored?
Array implementation
Cont…
Cont…
Output of the code
Time Complexity of Min/Max Heap
• Thanks

You might also like