vault backup: 2025-03-16 18:59:42
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# Consider a min heap with these elements: [4, 5, 6, 7, 8, 9, 10]. Insert 3 into this min heap.
|
||||
# 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:
|
||||
|
||||
@@ -8,10 +8,13 @@ In a **min heap**, the root node contains the smallest element, and every parent
|
||||
### 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
|
||||
/ \
|
||||
@@ -19,13 +22,17 @@ This corresponds to the following binary tree:
|
||||
/ \ / \
|
||||
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
|
||||
/ \
|
||||
@@ -35,6 +42,7 @@ This corresponds to the following binary tree:
|
||||
/
|
||||
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:
|
||||
@@ -42,6 +50,7 @@ Now, we need to **bubble up** the element `3` to restore the heap property. We c
|
||||
- The parent of `3` is `7` (index 3). Since `3 < 7`, we swap them.
|
||||
|
||||
After the swap, the heap becomes:
|
||||
|
||||
```
|
||||
4
|
||||
/ \
|
||||
@@ -57,6 +66,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
|
||||
/ \
|
||||
@@ -86,6 +96,7 @@ After the swap, the heap becomes:
|
||||
### **Final Array Representation**:
|
||||
|
||||
The final min heap as an array is:
|
||||
|
||||
```csharp
|
||||
[3, 4, 6, 5, 8, 9, 10, 7]
|
||||
```
|
||||
|
Reference in New Issue
Block a user