Question

A priority queue is implemented as a Max-Heap. Initially, it has 5 elements. The level-order traversal of the heap is: 10, 8, 5, 3, 2. Two new elements 1 and 7 are inserted into the heap in that order. The level-order traversal of the heap after the insertion of the elements is:

Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2014 answer key

Solution

Simulate successive heap insertions into the Max-Heap and read out the resulting array level by level.

  1. Initial Max-Heap Array Representation (1-indexed):

    • Indices: 1: 10, 2: 8, 3: 5, 4: 3, 5: 2
    • Level-order traversal: 10, 8, 5, 3, 2.
  2. Insert Element 1:

    • Place 11 at the next available position: index 66 (left child of index 33, which is 55).
    • Compare with parent at index 33 (55): since 1<51 < 5, max-heap property is satisfied.
    • Heap array: [10, 8, 5, 3, 2, 1].
  3. Insert Element 7:

    • Place 77 at the next available position: index 77 (right child of index 33, which is 55).
    • Compare with parent at index 33 (55): since 7>57 > 5, swap 77 and 55.
      • Index 33 becomes 77.
      • Index 77 becomes 55.
    • Compare new element at index 33 (77) with its parent at index 11 (1010):
      • Since 7<107 < 10, no further swap is needed.
    • Heap array: [10, 8, 7, 3, 2, 1, 5].
  4. The level-order traversal of the final heap is 10, 8, 7, 3, 2, 1, 5 (option A).

Final answer

A

Common trap

Swapping 7 all the way to the root without checking against parent 10.

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

Source

Paper
GATE 2014 Computer Science and Information Technology (CS) Session 2
Question
22 of 65, printed as CS Q.12
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.