You could also use a counting sort-like approach, if the array only contains small numbers for example (like if it's a character array):
inversions = 0
let count = array of size array.Length
for i = 0 to array.Length - 1 do
for j = array[i] + 1 to maxArrayValue do
inversions = inversions + count[j]
count[array[i]] = count[array[i]] + 1
Basically, keep a count of how many times each element appears. Then at each step i
, the number of inversions the i
th element generates is equal to the sum of all the elements bigger than i
that come before i
, which you can easily compute using the count you're keeping.
This will be O(n*eps)
where eps
is the domain of the elements in your array.
This is definitely simpler in my opinion. As for efficiency, it's only good if eps
is small obviously. If it is, then it should be faster than other approaches since there's no recursion.