ProgrammingVery hardGoldman Sachs OA · Capgemini
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer a[5] = {2, 3, 4, 5, 1}, passes = 0, n = 5
Boolean swapped
for (each i from 0 to n - 2)
swapped = false
passes = passes + 1
for (each j from 0 to n - 2 - i)
if (a[j] > a[j + 1])
swap(a[j], a[j + 1])
swapped = true
end if
end for
if (not swapped)
break
end if
end for
Print passes- A. 1
- B. 2
- C. 5
- D. 4
Correct answer: D. 4
A small number at the end moves left only one place per pass of bubble sort, so the 1 needs 4 passes to reach the front, and every one of them swaps. The early exit never triggers, and the loop ends after its 4 allowed passes.
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? (All variables are integers, so / is integer division) Integer n = 77, steps = 0, p…
- What will be the output of the following pseudocode? (<< is left shift, | is bitwise OR, & is bitwise AND) Integer x = 0 for (each i from…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer mults = 0 Function…
- What will be the output of the following pseudocode? String s = "(()(()))()" Integer depth = 0, best = 0, pairs = 0 for (each i from 0 to…
- What will be the output of the following pseudocode? (^ is XOR, & is AND) Integer s = 0, x, p for (each i from 1 to 20) x = i p = 0 while…
- What will be the output of the following pseudocode? Integer P[4][4] = all 0 Integer A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} for (each…