I've done the MergeSort algorithm, but I don't know how to count the swaps.
My code is:
def mergesortInv(list):
if len(list) < 2:
return list
else:
middle = len(list) // 2
left = mergesortInv(list[:middle]) #definim les dues meitats
right = mergesortInv(list[middle:])
swaps=???
return mergeInv(left, right,swaps)
def mergeInv(left, right,swaps):
if len(left) < 1:
return right
if len(right) < 1:
return left
if left[0] <= right[0]:
return [left[0]] + mergeInv(left[1:],right,swaps)
else:
return [right[0]] + mergeInv(left,right[1:],swaps)
The output of this algorithm would be the sorted list(the algorithm works in this part) and the number of swaps: mergesortInv(list) == ([1, 2, 3, 4, 5, 7, 8], 6)
6 is the number of swaps.