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]- A. 1 2 5 9
- B. 2 1 5 7
- C. 1 5 7 2
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer table[7] = all -1, probes = 0, h for each key in {50, 700, 76, 85, 92, 73…
- What is the time complexity of the following pseudocode, as a function of n? for (i = 1; i < n; i = i 2) for (j = 0; j < i; j = j + 1)…
- What is the time complexity of the following pseudocode, as a function of n (n > 2)? while (n > 2) n = squareRoot(n) // integer square…
- What will be the output of the following pseudocode? Integer coins[3] = {1, 2, 5} Integer ways[0..6] = all 0 ways[0] = 1 for (each a from…
- What will be the output of the following pseudocode? (code(c) gives a letter's character code; strings are indexed from 0) String s =…
- What will be the output of the following pseudocode? // list: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL Node slow = head, fast = head while…