Skip to content
Official PYQ · 2015

GATE CS 2015 Set 1 Q32 — Binary Heaps

Explain with AI

Consider a max heap, represented by the array: 40,30,20,10,15,16,17,8,440, 30, 20, 10, 15, 16, 17, 8, 4.

Array index123456789Value4030201015161784\begin{array}{|l|l|}\hline \text{Array index} & \text{1} & \text{2} & \text{3} & \text{4} & \text{5} & \text{6} & \text{7} & \text{8} & \text{9} \\ \hline \text{Value} & \text{40} & \text{30} & \text{20} & \text{10} &\text{15} & \text{16} & \text{17} & \text{8} & \text{4} \\ \hline \end{array}

Now consider that a value 3535 is inserted into this heap. After insertion, the new heap is

Choose one option
View worked solution

Answer: B

To insert a value into a max-heap, we follow a two-step process:

  1. Insert the new element at the next available position in the complete binary tree (at the end of the array).
  2. Perform a heapify-up (or bubble-up) operation to restore the max-heap property.

Step-by-Step Execution:

1. Initial Array (1-indexed):

1234567894030201015161784\begin{array}{|c|c|c|c|c|c|c|c|c|} \hline 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 \\ \hline 40 & 30 & 20 & 10 & 15 & 16 & 17 & 8 & 4 \\ \hline \end{array}

2. Insert 3535 at index 10:

12345678910403020101516178435\begin{array}{|c|c|c|c|c|c|c|c|c|c|} \hline 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ \hline 40 & 30 & 20 & 10 & 15 & 16 & 17 & 8 & 4 & \mathbf{35} \\ \hline \end{array}

3. Heapify-up from index 10:

  • The parent of index 1010 is index ⌊10/2⌋=5\lfloor 10/2 \rfloor = 5 (value 1515).
  • Since 35>1535 > 15, we swap them:

12345678910403020103516178415\begin{array}{|c|c|c|c|c|c|c|c|c|c|} \hline 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ \hline 40 & 30 & 20 & 10 & \mathbf{35} & 16 & 17 & 8 & 4 & \mathbf{15} \\ \hline \end{array}

  • The parent of index 55 is index ⌊5/2⌋=2\lfloor 5/2 \rfloor = 2 (value 3030).
  • Since 35>3035 > 30, we swap them:

12345678910403520103016178415\begin{array}{|c|c|c|c|c|c|c|c|c|c|} \hline 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ \hline 40 & \mathbf{35} & 20 & 10 & \mathbf{30} & 16 & 17 & 8 & 4 & 15 \\ \hline \end{array}

  • The parent of index 22 is index ⌊2/2⌋=1\lfloor 2/2 \rfloor = 1 (value 4040).
  • Since 35≤4035 \le 40, the max-heap property is satisfied. The process terminates.

The final array representation of the max-heap is:
40,35,20,10,30,16,17,8,4,1540, 35, 20, 10, 30, 16, 17, 8, 4, 15

Thus, the correct option is B.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Binary Heaps questions