0

我正在实现具有反转计数的合并排序。我的代码适用于我的小输入文件(10 个元素),但是当它达到 100000 时,它似乎从粗略搜索返回了不正确的答案。有时更大,有时更小。有人知道吗?

我的代码返回 2402298631。输入文件位置 http://spark-public.s3.amazonaws.com/algo1/programming_prob/IntegerArray.txt

def msort_inv2(m):

    global count

    if len(m) <= 1:
        return m
    result = []
    middle = int(len(m)/2)

    left = msort_inv2(m[:middle])
    right = msort_inv2(m[middle:])

    while (len(left) > 0) or (len(right) > 0):
        if (len(left) > 0) and (len(right) > 0):
            if left[0] > right[0]:
                result.append(right[0])
                count = count + len(left)
                right.pop(0)
            else:
                result.append(left[0])
                left.pop(0)
        elif len(right) > 0:
            for i in right:
                result.append(i)
                right.pop(0)
        else:
            for i in left:
                result.append(i)
                left.pop(0)
    return result
4

1 回答 1

1

the bug exists in following portion

    elif len(right) > 0:
        for i in right:     # bug !!!!
            result.append(i)
            right.pop(0)
    else:
        for i in left:
            result.append(i)
            left.pop(0)

the correction would be like this

    elif len(right) > 0:
        result.extend(right)
        right = []
    else:
        result.extend(left)
        left = []

for loop in an array and pop out item at the same time, will cause weird behavior in python.

于 2014-08-20T21:58:02.353 回答