ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def sort_count(a):
    if len(a) <= 1:
        return a, 0
    m = len(a) // 2
    l, x = sort_count(a[:m])
    r, y = sort_count(a[m:])
    out, i, j, c = [], 0, 0, x + y
    while i < len(l) and j < len(r):
        if l[i] <= r[j]:
            out.append(l[i])
            i += 1
        else:
            out.append(r[j])
            j += 1
            c += len(l) - i
    out += l[i:] + r[j:]
    return out, c
print(sort_count([2, 4, 1, 3, 5])[1], sort_count([5, 4, 3])[0])
  1. A. 4 [3, 4, 5]
  2. B. 3 [5, 4, 3]
  3. C. 2 [3, 4, 5]
  4. D. 3 [3, 4, 5]

Correct answer: D. 3 [3, 4, 5]

Merge sort counts inversions while merging: each time an item from the right half moves first, every item still left in the left half forms an inversion with it. The first list has 3 inversions and the second sorts to 3, 4, 5.

More Python Programming questions

Exams that ask this topic