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

  1. Divide: Divide the list into two equal pieces, say and
  2. Conquer: Count the number of inversions within and
  3. 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

  1. Divide: Divide the list into two equal pieces, say and
  2. Conquer: Sort and count the number of inversions within and
  3. 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