Solution: Number of Inversions

Solve the Number of Inversions Problem.

We'll cover the following...

Solution

Let’s try the most frequently used type of the divide-and-conquer strategy. Split the input sequence into two halves, LeftHalfLeftHalf and RightHalfRightHalf, and make a recursive call for each of them. This allows us to compute all inversions that lie in the same half. But it does not reveal the numbers of split inversions, i.e., the number of pairs (ai,aj)(a_i, a_j) such that aia_i lies in the left half, aja_j lies in the right half, and ai>aja_i >a_j.

Stop and think: Consider an element xx in LeftHalfLeftHalf. What is the number of split inversions that xx belongs to?

Given an array ListList and an integer xx, let ListxList_x be the number of elements in ListList that are smaller than xx. Since the answer to the question above is RightHalfxRightHalf_x, our goal is to rapidly compute ListxList_x.

It is equal to the number of elements in RightHalfRightHalf ...