92 lines
1.8 KiB
Markdown
92 lines
1.8 KiB
Markdown
# 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:
|
|
|
|
1. **Insert the element at the end** of the heap (maintaining the complete binary tree property).
|
|
2. **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:
|
|
```csharp
|
|
[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:
|
|
```csharp
|
|
[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` is `7` (index 3). Since `3 < 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` is `5` (index 1). Since `3 < 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:
|
|
```csharp
|
|
[3, 4, 6, 5, 8, 9, 10, 7]
|
|
```
|