ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (Arrays are indexed from 0)

What will be the output of the following pseudocode? (Arrays are indexed from 0)
Integer a[5] = {1, 2, 3, 4, 5}, comps = 0
Procedure qs(Integer lo, Integer hi)
    if (lo >= hi)
        return
    end if
    Integer p = a[hi], i = lo - 1
    for (each j from lo to hi - 1)
        comps = comps + 1
        if (a[j] <= p)
            i = i + 1
            swap(a[i], a[j])
        end if
    end for
    swap(a[i + 1], a[hi])
    qs(lo, i)
    qs(i + 2, hi)
End Procedure
qs(0, 4)
Print comps
  1. A. 5
  2. B. 10
  3. C. 8
  4. D. 15

Correct answer: B. 10

With the last element as pivot, a sorted array is the worst case: each partition leaves everything on one side. The comparisons are 4 + 3 + 2 + 1 = 10, i.e. n(n − 1)/2.

More Pseudocode and Code Tracing questions

Exams that ask this topic