Professional Documents
Culture Documents
• Min-heap: in min heap the key present at the root node must be
minimum among the keys present at all it’s children.
Operations in Heaps
The following are the essential operations you might use when implementing a heap data
structure:
extract: returns the value of an item and then deletes it from the heap.
3
Next insert 1 at the bottom of the heap
Swap the child node (1) with the parent node (3) because 1 is less than 3
1
3
Insert 6 in the bottom of the heap, and since 6 is greater than 1, no swapping
needed
1
3 6
Next insert 5 to the bottom of the heap, and since 5 is greater than 3,no swapping
needed.
1
3 6
5
Next insert 2 to the bottom of the heap, and since 2 is less than 3,we need to
swap
1
2 6
5 3
Next insert 4 to the bottom of the heap, and since 4 is less than 6,need to swap
2 4
5 3 6
Example of Max Heap
3 1 6 5 2 4
Array:
3
Next insert 1 at the bottom of the heap
Insert 6 in the bottom of the heap, and since 6 is greater than 3, swap it
1 3
Next insert 5 to the bottom of the heap, and since 5 is greater than 1,swap it
5 3
1
Next insert 2 to the bottom of the heap, and since 2 is less than 5,no swapping
5 3
1 2
Next insert 4 to the bottom of the heap, and since 4 is greater than 3,need to
swap
6
5 4
1 2 3
Exercise:
• Construct a max heap for the given array of elements-
1, 5, 6, 8, 12, 14, 16