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 version of merge sort to count the number of inversions. The trick is that while merging two sorted sub arrays you can come to know the elements which are out of place. If there are any elements in right subarray which need to go before the ones in left subarray, they are the inverted ones. I've written the code for this in python. You can check the explanation below it for better understanding. If you not able to understand merge sort I'd suggest you to revist merge sort after which this would be intuitive.
def merge_sort(l):
if len(l) <= 1:
return (0, l)
else:
mid = len(l) / 2
count_left, ll = merge_sort(l[0:mid])
count_right, lr = merge_sort(l[mid:])
count_merge, merged = merge(ll, lr)
total = count_left + count_right + count_merge
return total, merged
def merge(left, right):
li, ri = 0, 0
merged = []
count = 0
while li < len(left) and ri < len(right):
if left[li] < right[ri]:
merged.append(left[li])
li += 1
else:
count += 1
merged.append(right[ri])
ri += 1
if li < len(left):
merged.extend(left[li:])
elif ri < len(right):
merged.extend(right[ri:])
return count, merged
if __name__ == '__main__':
# example
l = [6, 1 , 2, 3, 4, 5]
print 'inverse pair count is %s'%merge_sort(l)[0]