Possible Duplicate:
Counting inversions in an array
This is an phone interview question: "Find the number of inversions in an array". I guess they mean O(Nlog N) solution. I believe it cannot be better than O(Nlog N) since this is the sorting complexity.
The answers to a similar question can be summarized as follows:
-
Calculate half the distance the elements should be moved to sort the array : copy the array and sort the copy. For each element of the original array
a[i]find it’s positionjin the sorted copy (binary search) and sum the halves the distancesabs(i - j)/2. -
Modify
merge sort: modifymergeto count inversions between two sorted arrays and run regularmerge sortwith that modifiedmerge.Does it make sense ? Are there other (maybe simpler) solutions ? Isn’t it too hard for a phone interview ?
It is actually an application of divide-and-conquer algorithm, and if you are familiar with it you can come up with the solution quickly.
Take [1 3 8 5 7 2 4 6] as an example, assume we have sorted array as [1 3 5 8] and [2 4 6 7], and now we need to combine the two arrays and get the number of total inversions.
Since we already have number of inversions in each sub-array, we only need to find out the number of inversions caused by array merging. Each time an element is inserted, for example, 2 inserted into [1 # 3 5 8], you can know how many inversions there are between the first array and the element 2 (3 pairs in this example). Then you can add them up to get the number of inversions caused by merging.