ProgrammingVery hardTCS NQT · Accenture
Array a = [3, 1, 2, 5, 4] is sorted by bubble sort: in each pass adjacent pairs out of order are swapped (a[j] > a[j+1]). What is the total number of swaps printed?
Array a = [3, 1, 2, 5, 4] is sorted by bubble sort: in each pass adjacent pairs out of order are swapped (a[j] > a[j+1]). What is the total number of swaps printed?
swaps = 0
repeat for each pass over j = 0 to n - 2
if a[j] > a[j+1] then swap a[j] and a[j+1]; swaps = swaps + 1
Print swaps- A. 20
- B. 3
- C. 7
- D. 10
Correct answer: B. 3
Each swap removes exactly one inversion, and the inversions here are (3,1), (3,2) and (5,4), so three swaps happen. Counting comparisons gives 20, counting non-inversions gives 7, and counting the out-of-order adjacent pairs in each pass without swapping gives 10.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Items of weights 7, 3, 5, 2, 6 are considered in increasing weight order. Each item is taken if it still fits in the capacity 13. What is…
- For i from 0 to 30 inclusive, count the values of i with ii <= 30. What is printed? count = 0 for i = 0 to 30 if i i <= 30 then count =…
- Array [4, 1, 3, 2] is sorted by selection sort: for each position i, find the minimum of the unsorted part and swap it into position i…
- Sorted array a = [1, 2, 3, 5, 8, 9] and limit L = 10. Count the pairs of distinct positions i < j with a[i] + a[j] <= L using two…
- The string s = "aaabbbcc" is cut down so that no two adjacent letters are equal, by deleting characters. The greedy keeps a character when…
- A binary string s = "1100101" is to be made alternating. Two targets are possible: "0101010..." and "1010101...", each the same length as…