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 positionj
in the sorted copy (binary search) and sum the halves the distancesabs(i - j)/2
.Modify
merge sort
: modifymerge
to count inversions between two sorted arrays and run regularmerge sort
with that modifiedmerge
.Does it make sense ? Are there other (maybe simpler) solutions ? Isn't it too hard for a phone interview ?