Merge sort to count split inversions in Python

我是研究僧i 提交于 2019-11-30 14:48:53

Modify your mergesort function to disregard the intermediate splits.

def mergesort(lst):
    '''Recursively divides list in halves to be sorted'''
    if len(lst) == 1:
        return lst, 0
    middle = len(lst)/2
    left = mergesort(lst[:middle])[0]  # Ignore intermediate splits
    right = mergesort(lst[middle:])[0]  # Ignore intermediate splits
    sortedlist, splits = merge(left, right)
    return sortedlist, splits

There's a few things wrong in your code:

  • Don't int() the result of len() / 2. If you are using Python3, I'd directly use integer division with the // operator.
  • The comparison in the first line of mergesort() is wrong. Firstly, do not use is to compare for equality. The is operator is only intended for identity. If you have two different integers which have the same value, they are equal but not identical. For small integers, I believe that at least some Python dialects will intern the value, hence your comparison works, but you are relying on something that isn't guaranteed. Still, using == also doesn't work, because you forgot the case of the empty list.
  • I guess your actual problem ("wonky return value") is caused by the fact that you return two values that you store (as a tuple) under a single name and which you then pass as parameters to recursive merge() calls.
Jofel Bayron

Since, in your code merge returns a pair, mergesort must also return a pair. Enable to get the total split inversion in the list you must add the left half, right half and merge split inversions.

Here is the modification I have made in your code.

def mergesort(lst):
    '''Recursively divides list in halves to be sorted'''
    if len(lst) == 1:
        return lst, 0
    middle = len(lst)/2
    left, s1 = mergesort(lst[:middle])[0]  # Ignore intermediate splits
    right, s2 = mergesort(lst[middle:])[0]  # Ignore intermediate splits
    sortedlist, s3 = merge(left, right)
    return sortedlist, (s1+s2+s3)`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!