Skip to content

Instantly share code, notes, and snippets.

@blindFS
Created October 9, 2014 11:07
Show Gist options
  • Save blindFS/a8c7d9e404ac26ce8a88 to your computer and use it in GitHub Desktop.
Save blindFS/a8c7d9e404ac26ce8a88 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
count = 0
def merge_sort(li):
if len(li) < 2:
return li
m = len(li) / 2
return merge(merge_sort(li[:m]), merge_sort(li[m:]))
def merge(l, r):
global count
result = []
i = j = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
result.append(l[i])
i += 1
else:
result.append(r[j])
count = count + (len(l) - i)
j += 1
result.extend(l[i:])
result.extend(r[j:])
return result
with open('./data1.txt', 'r') as f:
lines = f.readlines()
unsorted = map(int, lines)
merge_sort(unsorted)
print count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment