I ran into an interesting algorithm problem:
Given an array of integer, find the number of un-ordered pairs in that array, say given {1, 3, 2}, the answer is 1 becau
You can use a modified merge-sort algorithm. Merging would look something like this.
merge(a, b):
i = 0
j = 0
c = new int[a.length+b.length]
inversions = 0
for(k = 0 ; k < Math.min(a.length, b.length); k++)
if(a[i] > b[j]):
inversions++
c[k] = b[j]
j++
else:
c[k] = a[i]
i++
//dump the rest of the longer array in c
return inversions
Merging is done in O(n) time. Time complexity of the whole merge sort is O(n log n)