Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (heap sort on a small array, showing the array after the first extraction)

What is printed? (heap sort on a small array, showing the array after the first extraction)
def sift(a, i, n):
    while 2 * i + 1 < n:
        c = 2 * i + 1
        if c + 1 < n and a[c + 1] > a[c]: c += 1
        if a[i] >= a[c]: break
        a[i], a[c] = a[c], a[i]; i = c
a = [3, 9, 2, 1, 4, 5]
for i in range(len(a) // 2 - 1, -1, -1): sift(a, i, len(a))
heap = a[:]
a[0], a[-1] = a[-1], a[0]; sift(a, 0, len(a) - 1)
print(heap, a)
  1. A. [9, 4, 5, 1, 3, 2] [5, 4, 3, 1, 2, 9]
  2. B. [9, 5, 4, 3, 2, 1] [5, 4, 3, 2, 1, 9]
  3. C. [9, 4, 5, 1, 3, 2] [2, 4, 5, 1, 3, 9]
  4. D. [9, 4, 5, 1, 3, 2] [5, 4, 2, 1, 3, 9]

Correct answer: D. [9, 4, 5, 1, 3, 2] [5, 4, 2, 1, 3, 9]

Heapify gives [9, 4, 5, 1, 3, 2]. Heap sort swaps the max (9) to the end and sifts the new root 2 down within the first 5 slots: 2 ↔ 5 → [5, 4, 2, 1, 3 | 9]. Heap sort is O(n log n) in place but not stable.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic