使用归并排序计算逆序对的算法,在哪些情况下会失败?

3
我已经编写了以下代码来计算数字数组中逆序对的数量。对于我测试过的输入,它给出了正确的结果,但仍然无法通过测试用例,我无法访问测试用例,也无法找出失败的用例,希望能得到帮助。
 def count_inversion(array):
        """
        counts number of inversions in array using divide and conquer
        an inversion is a pair (x,y) such that x > y, example in array
        [3,1,2] there are two inversions (3,1), (3,2)
        """
        length = len(array)
        if length == 1 or length == 0:
            return array,0
        elif length == 2:
            if array[0] > array[1]:
                array.sort()
                return array,1
            else:
                return array,0
        else:
            left_array,left_count = count_inversion(array[:length/2])
            right_array,right_count = count_inversion(array[length/2:])
            across_arr,across_count = count_split(left_array,right_array)
            return across_arr,left_count + right_count + across_count

def count_split(left,right):
    """
    counts the number of inversions across split pair
    left and right, by piggy backing on merge routine 
    of merge sort
    """
    l = 0 
    r = 0
    merge = []
    count = 0
    inversions = 0
    last_r = 0
    try:
        while True:
            if left[l] > right[r]:
                merge.append(right[r])
                if r == 0 or r == last_r:
                    inversions = 0
                inversions += 1
                r = r + 1
            else:
                merge.append(left[l])
                count = count + inversions
                l = l + 1
                last_r = r

    except IndexError:
        if r == len(right):
            while l < len(left):
                count += inversions
                merge.append(left[l])
                l = l + 1 
        else:
            while r < len(right):
                merge.append(right[r])
                r = r + 1
    return merge,count

if __name__ == '__main__':
    f = open('inversions.txt')
    arr = []
    for line in f:
        arr.append(int(line))
    # arr is a list of integers which are not sorted in any sense
    # we are required to count number of inversions in arr
    print count_inversion(arr)[1]
1个回答

3

尝试

3 4 6 1 2 5

你的答案是5。
真正的答案是7。

这看起来像是作业或在线评测,所以我会说你的错误可能在异常块中。


不是在异常块中出错,实际上错误出在我计算逆序对数量的方式上,但你的示例帮助我找到了错误。非常感谢 :) - Bunny Rabbit
明显错误N1:将异常块中第一个while循环的count += inversion替换为count += r。 - kilotaras

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接