I\'m designing an algorithm to do the following: Given array A[1... n]
, for every i < j
, find all inversion pairs such that A[i] > A[j]
I had a question similar to this for homework actually. I was restricted that it must have O(nlogn) efficiency.
I used the idea you proposed of using Mergesort, since it is already of the correct efficiency. I just inserted some code into the merging function that was basically: Whenever a number from the array on the right is being added to the output array, I add to the total number of inversions, the amount of numbers remaining in the left array.
This makes a lot of sense to me now that I've thought about it enough. Your counting how many times there is a greater number coming before any numbers.
hth.