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[8] = {2, 0, 1, 2, 1, 0, 2, 1}
Integer lo = 0, mid = 0, hi = 7
while (mid <= hi)
if (a[mid] == 0)
swap(a[lo], a[mid])
lo = lo + 1
mid = mid + 1
else if (a[mid] == 1)
mid = mid + 1
else
swap(a[mid], a[hi])
hi = hi - 1
end if
end while
Print lo, hi- A. 2 5
- B. 3 5
- C. 2 4
- D. 3 4
Correct answer: C. 2 4
This is the Dutch-national-flag partition. It ends with all 0's in a[0..lo − 1] and all 2's in a[hi + 1..7]. There are two 0's and three 2's, so lo = 2 and hi = 7 − 3 = 4.
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? (Arrays are indexed from 0) Integer a[7] = {7, 2, 9, 4, 1, 8, 5} Integer pivot =…
- What will be the output of the following pseudocode? Integer a[9] = {3, 3, 4, 2, 4, 4, 2, 4, 2} Integer cand = 0, cnt = 0 for (each i from…
- What will be the output of the following pseudocode? Integer a[7] = {16, 17, 4, 3, 5, 2, 1} Integer mx = a[6], c = 1 for (each i from 5…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer nxt[6] = {3, 5, 0, 1, 2, 4} Integer x = 0, steps…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[6] = {4, 5, 2, 25, 7, 8}, res[6] Stack st =…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer h[12] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}…