Write an algorithm to construct min heap.
Answers
Answer:
Step 1 − Create a new node at the end of heap. Step 2 − Assign new value to the node. Step 3 − Compare the value of this child node with its parent. Step 4 − If value of parent is less than child, then swap them.
Step-by-step explanation:
Heap is a special case of balanced binary tree data structure where the root-node key is compared with its children and arranged accordingly. If α has child node β then −
key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap. Based on this criteria, a heap can be of two types −
Min-Heap − Where the value of the root node is less than or equal to either of its children.
Max Heap
Max-Heap − Where the value of the root node is greater than or equal to either of its children.