ProgrammingHardAccenture · Cognizant pattern
How many swaps does this pseudocode perform? (Arrays are indexed from 0.)
How many swaps does this pseudocode perform? (Arrays are indexed from 0.)
Integer arr[5] = {5, 1, 4, 2, 8}
Integer swaps = 0
for (each i from 0 to 3)
for (each j from 0 to 3 - i)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1])
swaps = swaps + 1
end if
end for
end for
Print swaps- A. 10
- B. 5
- C. 4
- D. 3
Correct answer: C. 4
Each bubble-sort swap fixes exactly one inversion, so the number of swaps equals the number of inversions: (5,1), (5,4), (5,2), (4,2) = 4. The 10 comparisons are the trap.
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.) Function f(Integer n) if (n…
- What will be the output of the following pseudocode? Integer a = 3, b b = a a a = b - a b = b + a Print a mod b, b mod a
- How many times is count incremented? Integer n = 4, count = 0 for (each i from 1 to n) for (each j from 1 to i i) if (j mod i == 0) for…
- What will be the output? (&& does not evaluate its right side when the left side is false.) Integer c = 0, s = 0 Function inc() c = c + 1…
- What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right…
- Two sorted arrays a = {1, 4, 7} and b = {2, 3, 8, 9} are merged. How many element comparisons does the pseudocode make? Integer i = 0, j =…