Вот моя реализация внутри функции класса.Это также считает инверсии.Вы можете раскомментировать операторы, чтобы увидеть альтернативный способ отслеживания инверсий.
class MergeSort(object):
'''
Instantiates an array into the object from which the method 'merge_sort' can be called.
Returns number of inversions and sorted array.
>>>x = MergeSort([1,6,5,2,10,8,7,4,3,9])
>>>x.merge_sort()
(20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
'''
def __init__(self, array):
self.array = array
def merge_sort(self):
count = 0
#count_ = []
if len(self.array) > 1:
m = len(self.array)//2
left = self.array[:m]
right = self.array[m:]
leftsorter = MergeSort(left)
leftsorter = leftsorter.merge_sort()
rightsorter = MergeSort(right)
rightsorter = rightsorter.merge_sort()
# Two different ways to track inversions
# numeric counter, better way
count += leftsorter[0]
count += rightsorter[0]
# list counter
#count_.append(leftsorter[0])
#count_.append(rightsorter[0])
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
self.array[k] = left[i]
i += 1
else:
self.array[k] = right[j]
j += 1
count += len(left[i:])
#count_.append(len(left[i:]))
k += 1
while i < len(left):
self.array[k] = left[i]
i += 1
k += 1
while j < len(right):
self.array[k] = right[j]
j += 1
k += 1
return count, self.array, #sum(count_)
, который работает таким образом.
array = [1,6,5,2,10,8,7,4,3,9]
x = MergeSort(array)
x.merge_sort()
Out[ ]:
(20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])