0% found this document useful (0 votes)
9 views4 pages

Examples

The document provides two examples of inserting elements into a binary heap. In Example 1, the elements 50, 30, 40, 10, and 20 are inserted without any swaps needed, resulting in a final heap of 50, 30, 40, 10, 20. In Example 2, the elements 10, 20, 5, 30, and 15 are inserted with several swaps, resulting in a final heap of 30, 20, 5, 10, 15.

Uploaded by

itx31368
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views4 pages

Examples

The document provides two examples of inserting elements into a binary heap. In Example 1, the elements 50, 30, 40, 10, and 20 are inserted without any swaps needed, resulting in a final heap of 50, 30, 40, 10, 20. In Example 2, the elements 10, 20, 5, 30, and 15 are inserted with several swaps, resulting in a final heap of 30, 20, 5, 10, 15.

Uploaded by

itx31368
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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

You might also like