Let be a given list/array of numbers.
Definition
Two numbers and form an inversion if but

The number of inversions measures the “sortedness” of the array
- Less number of inversions = array is close to sorted
- More number of inversions = array is far from sorted
Naive Algorithm: Needs time as it checks if each of the pairs is an inversion or not.
Inspired by MergeSort
Three steps for divide-and-conquer algorithm
- Divide: Divide the list into two equal pieces, say and
- Conquer: Count the number of inversions within and
- Combine: Count the number of inversions where one number is from and other number is from
Analysis
Let be time needed to count number of inversions from a given list of numbers
- We need for the Divide step
- We need time for the Conquer step
- The Combine step needs time as
- Recurrence is
time algorithm to count number of inversions
We do the following improvements
- Divide: Divide the list into two equal pieces, say and
- Conquer: Sort and count the number of inversions within and
- Combine:
- We can assume that and both are sorted
- Count the number of inversions where one number is from and other number is from
Analysis
Let be time needed to count number of inversions from a given list of numbers
- We need for the Divide step
- We need time for the Conquer step
- It can be shown that the Combine step now needs only time as both and are sorted
- Recurrence is
- Same as that for MergeSort, and solves to
Wed design an algorithm Sort-and-Count(L) which takes as an input a list and outputs two things:
- The number of inversions in
- The list which is sorted version of L