GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 17(b)

Construct worst-case swap orders

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

GATE 2000, Q17(b) Descriptive
Report issue

Searching, Sorting & Selection

Question 17(b), 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. Give an order attaining the worst-case minimum.
Question 17(b), 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. Give an order attaining the worst-case minimum.
Tap to enlarge
Answer & solution

Answer: Arbitrary: 111100222001. Adjacent-only: 222111110000. (no official key was published)

For arbitrary swaps, choose [1,1,1,1 | 0,0,2,2,2 | 0,0,1], with target-zone lengths 4,5,3. The counts are four 0s, five 1s, three 2s. Number positions 1 through 12. One seven-swap sorting sequence is (1,5),(2,6),(7,12),(3,10),(8,10),(4,11),(9,11). After the first three swaps, the unsorted portion consists of two cycles, each carrying a 1 in the 0-zone, a 2 in the 1-zone and a 0 in the 2-zone. Each takes two swaps. All 12 entries were initially misplaced, so six swaps would require every swap to fix two errors. Only three opposite pairs are available, and a residual 3-cycle cannot be fixed in that way. Thus seven are necessary as well as sufficient; the general upper bound is proved in part(a).
For adjacent-only swaps, choose [2,2,2,1,1,1,1,1,0,0,0,0]. It has 3*5 inversions of type(2,1), 3*4 of type(2,0), and 5*4 of type(1,0), for 47. No array with these multiplicities can have more inversions, because every unequal pair is already inverted here. An adjacent inversion-removal sort takes exactly 47 swaps. This descending arrangement is not the arbitrary-swap witness: allowing distant exchanges changes the optimization problem.

Original paper, page 9