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)
  1. A. [10, 5, 9, 4, 1, 3, 8]
  2. B. [10, 9, 8, 5, 4, 3, 1]
  3. C. [10, 4, 9, 5, 1, 8, 3]
  4. 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.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic