Last active
December 21, 2015 21:18
-
-
Save DeaconDesperado/6367191 to your computer and use it in GitHub Desktop.
Merge sort with inversion counting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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