Question

Consider a max heap, represented by the array:

Array Index 1 2 3 4 5 6 7 8 9
Value 40 30 20 10 15 16 17 8 4

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

Choose one option
Official answer and solution
Official answer
B
From
Official GATE 2015 answer key

Solution

Simulate standard binary max-heap insertion at the end of the array followed by heapify-up (bubble-up).

The initial 1-indexed heap array is:

A=[40,30,20,10,15,16,17,8,4]A = [40, 30, 20, 10, 15, 16, 17, 8, 4]

with size n=9n = 9.

  1. Append the new element 3535 at index 1010:

    A[10]=35.A[10] = 35.
  2. Compare A[10]A[10] with its parent at ⌊10/2⌋=5\lfloor 10/2 \rfloor = 5 (A[5]=15A[5] = 15):
    Since 35>1535 > 15, swap A[10]A[10] and A[5]A[5]:

    A=[40,30,20,10,35,16,17,8,4,15].A = [40, 30, 20, 10, \mathbf{35}, 16, 17, 8, 4, \mathbf{15}].
  3. Compare new A[5]=35A[5] = 35 with its parent at ⌊5/2⌋=2\lfloor 5/2 \rfloor = 2 (A[2]=30A[2] = 30):
    Since 35>3035 > 30, swap A[5]A[5] and A[2]A[2]:

    A=[40,35,20,10,30,16,17,8,4,15].A = [40, \mathbf{35}, 20, 10, \mathbf{30}, 16, 17, 8, 4, 15].
  4. Compare new A[2]=35A[2] = 35 with its parent at ⌊2/2⌋=1\lfloor 2/2 \rfloor = 1 (A[1]=40A[1] = 40):
    Since 40>3540 > 35, the max-heap property is satisfied and insertion terminates.

The resulting array is:

40,35,20,10,30,16,17,8,4,15.40, 35, 20, 10, 30, 16, 17, 8, 4, 15.

This matches option B.

Final answer

B

Common trap

Stopping bubble-up after only one swap, failing to compare with the grandparent node at index 2.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 1
Question
42 of 65, printed as CS Q.32
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.