Today I was looking the latest exam of the local informatics olympiad and I found a interesting problem. Briefly, it asks to, given an integer array, count how many inversions i
The best result in the literature is an O(n √(log n)) algorithm due to Chan and Patrascu. No idea about the constant.
If we assume the number of bits used to represent the integer is constant (say 32 or 64 bits), this can be solved in O(N) time.
Here is an example python implementation.
http://ideone.com/g57O87
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([5, 4, 3, 2, 1])
We are able to achieve less than O(N x Log(N)) time complexity, as we are using idea behind a non-comparative sorting algorithm, radix sort, to get the count.
O(n log n) is the best as far as I know.
A detailed explanation was given here:
http://www.geeksforgeeks.org/counting-inversions/