Maths WorkshopMaths problems with full solutions
Exercise 1254Combinatorics › Counting principlesM1Added 4 Nov 2026

Sorting by adjacent swaps needs exactly the number of inversions

#permutations#inversions#sorting#monovariant

Statement

An inversion of a sequence a1,…,ana_1,\dots,a_n of distinct numbers is a pair i<ji<j with ai>aja_i>a_j. Prove that the minimal number of swaps of two adjacent entries needed to sort the sequence into increasing order equals its number of inversions. What is the largest value this number can take for nn entries?

Hint

How does one adjacent swap change the number of inversions? And if the sequence is not sorted, is there always a swap that reduces it?

Show solutionHide solution

Solution

Effect of a swap. Swap aia_i and ai+1a_{i+1}. The relative order of this pair changes, so the pair is an inversion after the swap iff it was not before. Every other pair keeps the same relative order. So the number of inversions changes by exactly ±1\pm1.

Lower bound. The sorted sequence has 00 inversions. If the sequence has II inversions, any sequence of swaps sorting it must decrease the count from II to 00 in steps of ±1\pm1, so it has at least II swaps.

Upper bound. If I>0I>0, the sequence is not sorted, so there is an index ii with ai>ai+1a_i>a_{i+1}. Swapping them decreases II by 11. Repeating, we sort the sequence in exactly II swaps.

Maximum. The number of inversions is at most the number of pairs, (n2)\binom n2, with equality for the decreasing sequence.

Example. 5,4,3,2,15,4,3,2,1 has 1010 inversions and needs 1010 swaps; 2,3,12,3,1 has 22 inversions.

Remark. The parity of the number of inversions is the sign of the permutation.

Lesson. A quantity that changes by exactly ±1\pm1 per step (a monovariant) gives matching lower and upper bounds.