Skip to content

Instantly share code, notes, and snippets.

@st0le
Created August 30, 2014 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st0le/0e9ae7027d7cc106aae5 to your computer and use it in GitHub Desktop.
Save st0le/0e9ae7027d7cc106aae5 to your computer and use it in GitHub Desktop.
Inversion Count - Merge Sort
def inversionCount_2(A):
def inversionCount_2(A,l,r):
if l >= r: return 0
m = (l + r) / 2
# recurse and store inversion counts for the halfs
invCount = inversionCount_2(A,l,m) + inversionCount_2(A,m + 1,r)
merged = []
i,j = l,m + 1
while i <= m and j <= r:
if A[i] < A[j]:
merged.append(A[i])
i += 1
else:
invCount += m - i + 1 #A[j] < A[i..m]
merged.append(A[j])
j += 1
merged.extend(A[i:m + 1]) # rest of first half
merged.extend(A[j:r + 1]) # rest of the second half
for i in xrange(l,r + 1): #copy from aux to Arr
A[i] = merged[i - l]
return invCount
return inversionCount_2(A,0,len(A) - 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment