Skip to content

Instantly share code, notes, and snippets.

@Yossarian0916
Last active May 26, 2019 04:50
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 Yossarian0916/08635da76dfc446c95e66d09b66e4b37 to your computer and use it in GitHub Desktop.
Save Yossarian0916/08635da76dfc446c95e66d09b66e4b37 to your computer and use it in GitHub Desktop.
count the inversions of a given array, for example, if the a is greater than b, but the index of a is smaller than b, this makes one inversion
"""
compute the number of inversions of the given array
running time is O(nlogn)
using divide and conquer
"""
def count_split_inv(array, left, right):
count = 0
i, j = 0, 0
length = len(left) + len(right)
# sentinal variable
left.append(float('inf'))
right.append(float('inf'))
for k in range(length):
if left[i] < right[j]:
array[k] = left[i]
i += 1
else:
array[k] = right[j]
count += len(left) - 1 - i
j += 1
return count
def count_inversion(array):
if len(array) == 1:
return 0
else:
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
a = count_inversion(left)
b = count_inversion(right)
c = count_split_inv(array, left, right)
return a + b + c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment