Skip to content

Instantly share code, notes, and snippets.

@DeaconDesperado
Last active December 21, 2015 21:18
Show Gist options
  • Save DeaconDesperado/6367191 to your computer and use it in GitHub Desktop.
Save DeaconDesperado/6367191 to your computer and use it in GitHub Desktop.
Merge sort with inversion counting
ints = [int(x) for x in open('IntegerArray.txt').read().split()]
def merge_and_count(a, b):
assert a == sorted(a) and b == sorted(b)
c = []
count = 0
i, j = 0, 0
while i < len(a) and j < len(b):
c.append(min(b[j], a[i]))
if b[j] < a[i]:
count += len(a) - i
j+=1
else:
i+=1
c += a[i:] + b[j:]
return count, c
def sort_and_count(li):
if len(li) == 1: return 0, li
n = len(li) // 2
a, b = li[:n], li[n:]
ra, a = sort_and_count(a)
rb, b = sort_and_count(b)
r, li = merge_and_count(a, b)
return ra+rb+r, li
print sort_and_count(ints)[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment