Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
A max-heap is built with heapify on the array below (0-based, children 2i+1 and 2i+2). What is the resulting array?
A max-heap is built with heapify on the array below (0-based, children 2i+1 and 2i+2). What is the resulting array?
def sift(a, i, n):
while True:
l, r, big = 2 * i + 1, 2 * i + 2, i
if l < n and a[l] > a[big]: big = l
if r < n and a[r] > a[big]: big = r
if big == i: return
a[i], a[big] = a[big], a[i]; i = big
a = [4, 10, 3, 5, 1, 8, 9]
for i in range(len(a) // 2 - 1, -1, -1): sift(a, i, len(a))
print(a)- A. [10, 5, 9, 4, 1, 3, 8]
- B. [10, 9, 8, 5, 4, 3, 1]
- C. [10, 4, 9, 5, 1, 8, 3]
- D. [10, 5, 9, 4, 1, 8, 3]
Correct answer: D. [10, 5, 9, 4, 1, 8, 3]
Bottom-up heapify sifts down from the last internal node: index 2 (3) swaps with 9; index 1 (10) is already larger than 5 and 1; index 0 (4) swaps with 10, then with 5. Result [10, 5, 9, 4, 1, 8, 3]. Bottom-up heapify is O(n), not O(n log n). A max-heap is not a sorted array.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- From the max-heap [50, 30, 40, 10, 20, 35, 25], delete the maximum once. What is the array? python import heapq h = [-x for x in [50, 30…
- What is printed? (count leaves, internal nodes and full nodes of a binary tree) python T = {1: (2, 3), 2: (4, None), 3: (5, 6), 4: (None…
- A binary tree has preorder A B D E C F G and inorder D B E A F C G. What is its postorder? python def post(pre, ino): if not pre: return…
- How many structurally different binary trees have n = 4 nodes, and how many distinct labelled binary trees can be formed from 4 distinct…
- What is printed? (number of nodes in a complete binary tree in O(log² n)) python def count(nnodes): # implicit complete tree with nodes…
- What is printed? (AVL: which rotation is needed after inserting 30, 10, 20 into an empty AVL tree?) python def balancecase(order): a, b, c…