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 that are smaller than xx. This way, we face the following problem: given a sequence of integers ListList and an integer xx, find the number of elements in ListList that are smaller than xx. We can do it in O(List)O(|List|) time in the case of the unordered array (since each element of the array has to be checked) and in O(logList)O(log |List|) time in the case of an ordered array by using the binary search.

Exercise break: Show how to implement a method CountSmaller(List,x)CountSmaller(List, x) for counting the number of elements of ListList that are smaller than xx in time O(log2List)O(log_2 |List|) ...