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- A. 5
- B. 10
- C. 8
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (mod keeps the sign of the dividend; code/char convert between letters and codes)…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer x = 1221, rev = 0…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer fact[10], count = 0…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 50, c = 0, p = 2…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 36, s = 0 for…
- What will be the output of the following pseudocode? (& is bitwise AND) Integer mask = 13, s, c = 0 s = mask while (s > 0) c = c + 1 s =…