Sorting by adjacent swaps needs exactly the number of inversions
Statement
An inversion of a sequence of distinct numbers is a pair with . 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 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 and . 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 .
Lower bound. The sorted sequence has inversions. If the sequence has inversions, any sequence of swaps sorting it must decrease the count from to in steps of , so it has at least swaps.
Upper bound. If , the sequence is not sorted, so there is an index with . Swapping them decreases by . Repeating, we sort the sequence in exactly swaps.
Maximum. The number of inversions is at most the number of pairs, , with equality for the decreasing sequence.
Example. has inversions and needs swaps; has inversions.
Remark. The parity of the number of inversions is the sign of the permutation.
Lesson. A quantity that changes by exactly per step (a monovariant) gives matching lower and upper bounds.