Searching, Sorting & Selection
![Question 33, GATE 2025: For i=0,…,n−2, an algorithm scans j=0,…,n−i−2 and swaps A[j],A[j+1] whenever A[j]>A[j+1]. Its input is 30 distinct integers in descending order. How many swaps occur?](../../assets/questions/CS-2025-S1-Q33-1.webp)
Answer & solution
Official answer: 435
Approach: An adjacent out-of-order swap removes exactly one inversion, so count the input’s inversions.
An inversion is a pair of positions i<j with A[i]>A[j]. In descending order every pair of distinct positions is an inversion. There are C(30,2)=30×29/2=435 such pairs.
When two adjacent inverted values are swapped, their mutual inversion disappears. Their order relative to every other element contributes the same total as before, because no other element lies between the two positions. Thus each swap reduces the inversion count by exactly one. The shown bubble-sort passes finish in ascending order, with zero inversions, so exactly 435 swaps are required.
A pass-by-pass check gives the same result: the largest value moves right in 29 swaps, the next in 28, and so on down to 1. Summing 29+28+⋯+1 gives 435. Comparisons and swaps are different quantities in general, even though every comparison succeeds for this descending distinct input.