Curated · Divide & Conquer: Quicksort

MCQ · 1 mark · Problem PROG-DIVC-0281

Consider the following Python code (Lomuto partition, last element as pivot).
def partition(a, lo, hi):
    p, i = a[hi], lo - 1
    for j in range(lo, hi):
        if a[j] <= p:
            i += 1
            a[i], a[j] = a[j], a[i]
    a[i + 1], a[hi] = a[hi], a[i + 1]
    return i + 1
a = [5, 9, 2, 7, 3, 6]
partition(a, 0, 5)
print(a)
What does it print?
  1. A
    [5, 2, 3, 6, 9, 7]
  2. B
    [5, 2, 3, 6, 7, 9]
  3. C
    [2, 3, 5, 6, 7, 9]
  4. D
    [3, 5, 2, 6, 9, 7]

Solve it on GATE DA practice →More Searching & Sorting Algorithms problems

Show the worked solution\[\boxed{\text{elements} \le \text{pivot are swapped into } a[lo..i] \text{ in the order they are met}}\]Pivot 6. 5 stays at index 0; 9 is skipped; 2 is swapped with 9: \([5, 2, 9, 7, 3, 6]\); 7 is skipped; 3 is swapped with 9: \([5, 2, 3, 7, 9, 6]\).Finally the pivot is swapped with index 3: \([5, 2, 3, 6, 9, 7]\). The two sides are not sorted, only separated (options B and C assume sorting).Answer: A

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com