GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 17(a)

Bound worst-case sorting swaps

Algorithms · Searching, Sorting & Selection · Full GATE CSE 2000 paper

GATE 2000, Q17(a) Descriptive
Report issue

Searching, Sorting & Selection

Question 17(a), GATE 2000: An array has four 0s, five 1s and three 2s, and is to be sorted increasingly using swaps. GFG Q64 p9 permits nonadjacent swaps; GateForum Q17 p16 requires adjacent swaps. Solve both distinct source versions. Find the maximum, over initial orders, of the minimum required swaps.
Question 17(a), GATE 2000: An array has four 0s, five 1s and three 2s, and is to be sorted increasingly using swaps. GFG Q64 p9 permits nonadjacent swaps; GateForum Q17 p16 requires adjacent swaps. Solve both distinct source versions. Find the maximum, over initial orders, of the minimum required swaps.
Tap to enlarge
Answer & solution

Answer: 7 for arbitrary swaps; 47 for adjacent-only swaps. (no official key was published)

Arbitrary-swap version: partition the target positions into zones of sizes 4,5,3 for 0,1,2. A misplaced value j in zone i is a directed edge i→j. Incoming and outgoing edge counts balance at every zone. First cancel every opposite pair i→j,j→i with one swap, fixing two positions. Once opposite pairs are exhausted, remaining edges form consistently oriented 3-cycles, each fixed by two swaps. Let d be the number of canceled pairs and c the number of remaining 3-cycles. This uses d+2c swaps and moves M=2d+3c<=12 misplaced positions. Each 3-cycle uses one position in the 2-zone, so c<=3. For c=0,1,2,3, the bound d<=floor((12−3c)/2) gives d+2c<=6,6,7,7 respectively. Hence seven swaps always suffice.
Attainment: use 1111|00222|001, where bars show target zones. Its opposite pairs are two 0/1 pairs and one 1/2 pair, and the remaining six misplaced entries form two 3-cycles, so seven suffice. To see six cannot suffice, all 12 positions are initially wrong. Six swaps would have to fix two positions each, and thus every swap would need to exchange an opposite pair without creating any new error. There are only three opposite pairs initially; after removing those, the remaining directed 3-cycles have no such pair. Six swaps are therefore impossible. The worst-case optimum is exactly 7.
Adjacent-only version: the minimum number of swaps equals the inversion count because an adjacent swap changes that count by exactly 1, and swapping adjacent inverted pairs sorts while decreasing it each time. The largest inversion count is attained by descending groups 222111110000. Every unequal pair is then inverted: 3*5+3*4+5*4=15+12+20=47. Equal-value pairs contribute zero. This discrepancy is substantive; the paper is authenticated as the official wording.

Original paper, page 9