I came across a solution in Python for the problem Count inversions in the array, which uses "non-comparative sorting algorithm to get the count". It makes 2 recursive calls to a code which executes bitwise operations.
def inv_count(a, m=(1 << 32)):
if not m or not a:
return 0
count = 0
ones, zeros = [], []
for n in a:
if n & m:
ones.append(n & ~m)
else:
count += len(ones)
zeros.append(n & ~m)
m /= 2
return count + inv_count(ones, m) + inv_count(zeros, m)
print inv_count([1, 2, 3, 4, 5])
print inv_count([2, 4, 1, 3, 5])
print inv_count([5, 4, 3, 2, 1])
Is this solution truly linear O(n)?
Similar SO question claims it's not possible (Is there an algorithm to count array inversions in linear time?), and while there is lot of literature on divide-and-conquer algorithms (with O(n logn) complexity), I would thank for some reference regarding the solution above.