1.8 KiB
Executable File
1.8 KiB
Executable File
Consider a Min Heap with These Elements: [4, 5, 6, 7, 8, 9, 10]. Insert 3 into This Min Heap.
In a min heap, the root node contains the smallest element, and every parent node is less than its children. When we insert a new element into a min heap, we follow these steps:
- Insert the element at the end of the heap (maintaining the complete binary tree property).
- Bubble up (or sift up) the inserted element to restore the heap property by comparing it with its parent and swapping if necessary.
Given Min Heap:
The given min heap is represented as an array:
[4, 5, 6, 7, 8, 9, 10]
This corresponds to the following binary tree:
4
/ \
5 6
/ \ / \
7 8 9 10
Step 1: Insert 3 into the Heap
First, insert 3 at the end of the heap:
[4, 5, 6, 7, 8, 9, 10, 3]
This corresponds to the following binary tree:
4
/ \
5 6
/ \ / \
7 8 9 10
/
3
Step 2: Bubble Up
Now, we need to bubble up the element 3
to restore the heap property. We compare 3
with its parent and swap if necessary:
- The parent of
3
is7
(index 3). Since3 < 7
, we swap them.
After the swap, the heap becomes:
4
/ \
5 6
/ \ / \
3 8 9 10
/
7
Now, we continue the bubbling up process:
- The parent of
3
is5
(index 1). Since3 < 5
, we swap them.
After the swap, the heap becomes:
4
/ \
3 6
/ \ / \
5 8 9 10
/
7
Finally, we compare 3
with its parent 4
(index 0):
- Since
3 < 4
, we swap them.
After the swap, the heap becomes:
3
/ \
4 6
/ \ / \
5 8 9 10
/
7
Final Array Representation:
The final min heap as an array is:
[3, 4, 6, 5, 8, 9, 10, 7]