Solution: Number of Inversions
Solve the Number of Inversions Problem.
Solution
Let’s try the most frequently used type of the divide-and-conquer strategy. Split the input sequence into two halves, and , 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 such that lies in the left half, lies in the right half, and .
Stop and think: Consider an element in . What is the number of split inversions that belongs to?
Given an array and an integer , let be the number of elements in that are smaller than . Since the answer to the question above is , our goal is to rapidly compute .
It is equal to the number of elements in that are smaller than . This way, we face the following problem: given a sequence of integers and an integer , find the number of elements in that are smaller than . We can do it in time in the case of the unordered array (since each element of the array has to be checked) and in time in the case of an ordered array by using the binary search.
Exercise break: Show how to implement a method for counting the number of elements of that are smaller than in time ...