ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (All variables are integers, so / is integer division; heap[k / 2] is the parent of heap[k])

What will be the output of the following pseudocode? (All variables are integers, so / is integer division; heap[k / 2] is the parent of heap[k])
Integer heap[1..7], size = 0, k
Procedure insert(Integer x)
    size = size + 1
    heap[size] = x
    k = size
    while (k > 1 AND heap[k / 2] > heap[k])
        swap(heap[k / 2], heap[k])
        k = k / 2
    end while
End Procedure
insert(9) insert(5) insert(7) insert(2) insert(6) insert(1)
Print heap[1], heap[2], heap[3], heap[6]
  1. A. 1 2 5 9
  2. B. 2 1 5 7
  3. C. 1 5 7 2
  4. D. 1 5 2 7

Correct answer: D. 1 5 2 7

Min-heap insertion with sift-up: after 9, 5, 7 → {5, 9, 7}; 2 rises to the root → {2, 5, 7, 9}; 6 stays under 5 → {2, 5, 7, 9, 6}; 1 enters at position 6 (parent 7) and rises to the root → {1, 5, 2, 9, 6, 7}. Output 1 5 2 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic