Example 1
🔢 Elements to insert (in order):
50, 30, 40, 10, 20
Step 1: Insert 50 (heap was empty)
Insert at index = 0
Heap: 50
50
Step 2: Insert 30
Insert at index = 1
Parent = (1-1)/2 = 0 → 50
30 < 50 → no swap
Heap: 50, 30
50
/
30
Step 3: Insert 40
Insert at index = 2
Parent = (2-1)/2 = 0 → 50
40 < 50 → no swap
Heap: 50, 30, 40
50
/ \
30 40
Step 4: Insert 10
Insert at index = 3
Parent = (3-1)/2 = 1 → 30
10 < 30 → no swap
Heap: 50, 30, 40, 10
50
/ \
30 40
/
10
Step 5: Insert 20
Insert at index = 4
Parent = (4-1)/2 = 1 → 30
20 < 30 → no swap
Heap: 50, 30, 40, 10, 20
50
/ \
30 40
/ \
10 20
✅ Final Heap (Array)
50, 30, 40, 10, 20
Example 2
🔢 Elements:
10, 20, 5, 30, 15
Step 1: Insert 10
Heap is empty → just insert
Array: 10
10
Step 2: Insert 20
Insert at index 1
Parent = (1−1)/2 = 0 → 10
20 > 10 → swap
Array before swap: 10, 20
After swap: 20, 10
20
/
10
Step 3: Insert 5
Insert at index 2
Parent = (2−1)/2 = 0 → 20
5 < 20 → no swap
Array: 20, 10, 5
20
/ \
10 5
Step 4: Insert 30
Insert at index 3
Parent = (3−1)/2 = 1 → 10
30 > 10 → swap
Now at index 1
Parent = (1−1)/2 = 0 → 20
30 > 20 → swap again
Swaps:
20, 10, 5, 30
→ 20, 30, 5, 10
→ 30, 20, 5, 10
30
/ \
20 5
/
10
Step 5: Insert 15
Insert at index 4
Parent = (4−1)/2 = 1 → 20
15 < 20 → no swap
Final array: 30, 20, 5, 10, 15
30
/ \
20 5
/ \
10 15
✅ Final Answer
📦 Heap (Array form):
30, 20, 5, 10, 15
🌳 Heap (Tree form):
30
/ \
20 5
/ \
10 15