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)- A. [9, 4, 5, 1, 3, 2] [5, 4, 3, 1, 2, 9]
- B. [9, 5, 4, 3, 2, 1] [5, 4, 3, 2, 1, 9]
- C. [9, 4, 5, 1, 3, 2] [2, 4, 5, 1, 3, 9]
- 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.
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
- What is printed? (trie: count distinct prefixes / nodes) python words = ["tea", "ten", "to", "inn", "in", "i"] root, nodes = {}, 0 for w…
- What is printed? (count connected components with DFS on an adjacency list) python n = 8 edges = [(0, 1), (1, 2), (3, 4), (5, 6), (6, 7)…
- Floyd–Warshall on 4 vertices. What is the shortest distance from 0 to 3, and from 3 to 1? python INF = float('inf') d = [[0, 3, INF, 7]…
- Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)? python edges = [(0, 1…
- What is printed? (detect a cycle in an undirected graph with union-find) python def hascycle(n, edges): p = list(range(n)) def f(x): while…
- What is printed? (number of paths from source to target in a DAG with memoisation) python from functools import lrucache g = {0: [1, 2…